MongoDB CRUD Operations: Insert and Find Documents
Last Updated :
14 Oct, 2024
MongoDB is a NoSQL database that allows for flexible and scalable data storage using a document-based model. CRUD (Create, Read, Update, Delete) operations form the backbone of any database interaction and in MongoDB, these operations are performed on documents within collections.
In this article, we’ll learn two key CRUD operations such as Insert and Find. We’ll explore how to add new documents to a MongoDB collection and retrieve them efficiently.
Inserting Documents in MongoDB
To add data to MongoDB, we use the Insert operation. In MongoDB documents are stored in collections which are like tables in relational databases.
Documents are JSON-like structures consisting of key-value pairs, where we can insert data using the insertOne() or insertMany() methods.
1. Insert a Single Document Using insertOne()
The insertOne() method is used to insert a single document into a collection. The inserted document gets a unique _id field automatically if its not specified, which acts as the primary key.
Syntax:
db.collection.insertOne(document)
Example:
db.users.insertOne({
"name": "Alice",
"age": 30,
"email": "[email protected]"
})
Output:
{
"acknowledged": true,
"insertedId": ObjectId("60d5f2a8c2957f489c4f4d23")
}
In this example, a new document is added to the users collection with the fields name, age, and email. MongoDB will generate an _id for the document if not provided.
2. Insert Multiple Documents Using insertMany()
The insertMany() method allows us to insert multiple documents at once. Each document is stored as a separate record in the collection and all documents receive their unique _id values.
Syntax:
db.collection.insertMany([document1, document2, ...])
Example:
db.users.insertMany([
{ "name": "Bob", "age": 25, "email": "[email protected]" },
{ "name": "Charlie", "age": 35, "email": "[email protected]" }
])
Output:
{
"acknowledged": true,
"insertedIds": [
ObjectId("60d5f2b1c2957f489c4f4d24"),
ObjectId("60d5f2b1c2957f489c4f4d25")
]
}
This command inserts two documents into the users collection. Each document is independent, with its own fields and values.
Finding Documents in MongoDB
After inserting documents, the next common operation is to retrieve them from the collection. MongoDB provides the find() method to search for documents based on specific criteria.
1. Find All Documents Using find()
The find() method without any parameters retrieves all documents from a collection. By default, MongoDB will return all fields for each document unless specified otherwise.
Syntax:
db.collection.find()
Example:
db.users.find()
Output:
[
{ "_id": ObjectId("60d5f2a8c2957f489c4f4d23"), "name": "Alice", "age": 30, "email": "[email protected]" },
{ "_id": ObjectId("60d5f2b1c2957f489c4f4d24"), "name": "Bob", "age": 25, "email": "[email protected]" },
{ "_id": ObjectId("60d5f2b1c2957f489c4f4d25"), "name": "Charlie", "age": 35, "email": "[email protected]" }
]
This query retrieves all documents from the users collection.
2. Find Documents Based on Criteria
To search for specific documents, you can pass a filter (query) object to the find() method. The query object specifies the criteria that documents must match.
Syntax:
db.collection.find(query)
Example:
db.users.find({ "age": { "$gt": 30 } })
Output:
[
{ "_id": ObjectId("60d5f2b1c2957f489c4f4d25"), "name": "Charlie", "age": 35, "email": "[email protected]" }
]
3. Find a Single Document: findOne()
The findOne() method is used to retrieve a single document that matches the query criteria. If multiple documents match, only the first one found is returned.
Example:
db.users.findOne({ "name": "Alice" })
Output:
{ "_id": ObjectId("60d5f2a8c2957f489c4f4d23"), "name": "Alice", "age": 30, "email": "[email protected]" }
Conclusion
In MongoDB, inserting and finding documents are fundamental operations for managing data. With insertOne() and insertMany(), you can add single or multiple documents to a collection. The find() method allows you to retrieve documents based on a range of criteria, making it a powerful tool for querying your data. By using projections, you can control which fields to return, further optimizing your queries.
Similar Reads
MongoDB CRUD Operations using Replace and Delete Documents MongoDB offers essential operations for data management particularly through its Replace and Delete functionalities. These operations enable users to efficiently update documents by replacing them entirely or removing specific entries based on defined criteria.In this article, We will learn about Mo
6 min read
How to Find Documents by ID in MongoDB? In MongoDB, finding documents by their unique identifier (ID) is a fundamental operation that allows us to retrieve specific records efficiently. Each document in a MongoDB collection has a unique _id field, which serves as the primary key. In this article, we will explore how to find documents by I
3 min read
Model Relationships Between Documents in MongoDB MongoDB as a NoSQL database, offers a flexible, document-based structure that enables us to define relationships between documents in various ways. Unlike traditional relational databases that depend on tables and foreign keys, MongoDB supports multiple ways of representing relationships, providing
5 min read
MongoDB CRUD Operations CRUD operations Create, Read, Update, and Deleteâare essential for interacting with databases. In MongoDB, CRUD operations allow users to perform various actions like inserting new documents, reading data, updating records, and deleting documents from collections. Mastering these operations is funda
5 min read
How to insert single and multiple documents in Mongodb using Node.js ? MongoDB, the most popular NoSQL database, is an open-source document-oriented database. The term âNoSQLâ means ânon-relationalâ. It means that MongoDB isnât based on the table-like relational database structure but provides an altogether different mechanism for storage and retrieval of data. This fo
2 min read
What is the Format of Document in MongoDB? MongoDB, which is one of the most prominent NoSQL databases, uses a document-oriented data model. A document in MongoDB is a collection of key-value pairs, where keys are strings (field names) and values can be of various data types such as strings, numbers, arrays, boolean values, dates, or even ne
4 min read