CRUD Operations in MongoDB: A Comprehensive Guide
MongoDB is a NoSQL database that provides a flexible way to store and manage data in a document-oriented format. CRUD operations—Create, Read, Update, and Delete—are the core functions used to interact with MongoDB databases.
This guide covers how to perform CRUD operations in MongoDB using the MongoDB shell and MongoDB Compass.
1. Setting Up MongoDB
Before performing CRUD operations, ensure you have MongoDB installed and running on your system.
1.1 Install MongoDB
Download MongoDB from the official MongoDB website.
Install and start the MongoDB server (
mongod
).Open the MongoDB shell (
mongosh
) to interact with the database.
1.2 Create a Database
To switch to a database (or create one if it doesn’t exist):
use myDatabase
2. Create Operation (INSERT Data into MongoDB)
The insert operation allows you to add documents to a collection.
2.1 Insert a Single Document
db.users.insertOne({
name: "John Doe",
age: 30,
email: "john@example.com",
createdAt: new Date()
})
2.2 Insert Multiple Documents
db.users.insertMany([
{ name: "Alice", age: 25, email: "alice@example.com" },
{ name: "Bob", age: 28, email: "bob@example.com" }
])
Each document automatically gets a unique _id field.
3. Read Operation (Retrieve Data from MongoDB)
The find operation retrieves data from collections.
3.1 Find All Documents
db.users.find()
3.2 Find a Specific Document
db.users.findOne({ name: "Alice" })
3.3 Find Documents with Conditions
db.users.find({ age: { $gt: 25 } }) // Finds users older than 25
3.4 Find Specific Fields
db.users.find({ age: { $gt: 25 } }, { name: 1, email: 1, _id: 0 })
The { name: 1, email: 1, _id: 0 }
part selects specific fields.
4. Update Operation (Modify Data in MongoDB)
The update operation allows modifying existing documents.
4.1 Update a Single Document
db.users.updateOne(
{ name: "John Doe" },
{ $set: { age: 31 } }
)
The $set
operator updates only the specified fields.
4.2 Update Multiple Documents
db.users.updateMany(
{ age: { $lt: 30 } },
{ $set: { status: "Active" } }
)
Adds a status field to users younger than 30.
4.3 Replace an Entire Document
db.users.replaceOne(
{ name: "Alice" },
{ name: "Alice Smith", age: 26, email: "alice.smith@example.com" }
)
⚠ This replaces the document instead of updating specific fields.
5. Delete Operation (Remove Data from MongoDB)
The delete operation removes documents from a collection.
5.1 Delete a Single Document
db.users.deleteOne({ name: "Bob" })
5.2 Delete Multiple Documents
db.users.deleteMany({ age: { $gt: 50 } })
✔ Deletes all users older than 50.
6. Additional MongoDB CRUD Features
6.1 Using Sorting and Pagination
db.users.find().sort({ age: -1 }).limit(5)
✔ Sorts by age (descending order) and limits to 5 results.
6.2 Counting Documents
db.users.countDocuments()
✔ Returns the total number of documents in a collection.
6.3 Checking if a Document Exists
db.users.findOne({ email: "john@example.com" }) !== null
✔ Returns true
if the document exists.
7. Performing CRUD Operations in MongoDB Compass
MongoDB Compass provides a GUI to perform CRUD operations without using commands.
Open MongoDB Compass and connect to the database.
Select a collection (e.g.,
users
).Perform CRUD operations:
Click “Insert Document” to create a new entry.
Use the filter bar to search for documents.
Edit or delete documents directly.
✔ Compass is ideal for visualizing data.
8. Conclusion
CRUD operations in MongoDB provide a simple and flexible way to manage data. Understanding how to insert, retrieve, update, and delete documents is essential for working with MongoDB efficiently.
Key Takeaways:
insertOne()
,insertMany()
→ Add documents.find()
,findOne()
→ Retrieve documents.updateOne()
,updateMany()
,$set
→ Modify existing data.deleteOne()
,deleteMany()
→ Remove documents.