CRUD Operations
CRUD — Create, Read, Update, Delete — forms the backbone of every database interaction. This lesson walks through MongoDB's CRUD methods, from basic single-document operations to advanced bulk writes.
1. Create — Inserting Documents
// Insert a single document
db.students.insertOne({
name: "Neha Gupta",
age: 21,
course: "Computer Science"
})
// Insert multiple documents
db.students.insertMany([
{ name: "Aman Singh", age: 22, course: "Mechanical" },
{ name: "Divya Rao", age: 20, course: "Electronics" }
])
2. Read — Querying Documents
// Find all documents
db.students.find()
// Find with a filter
db.students.find({ course: "Computer Science" })
// Find one document
db.students.findOne({ name: "Neha Gupta" })
// Projection: return only specific fields
db.students.find({ course: "Computer Science" }, { name: 1, age: 1, _id: 0 })
3. Update — Modifying Documents
// Update a single document
db.students.updateOne(
{ name: "Neha Gupta" },
{ $set: { age: 22 } }
)
// Update multiple documents
db.students.updateMany(
{ course: "Mechanical" },
{ $set: { department: "Engineering" } }
)
// Replace an entire document
db.students.replaceOne(
{ name: "Aman Singh" },
{ name: "Aman Singh", age: 23, course: "Mechanical Engineering" }
)
| Update Operator | Purpose |
|---|---|
$set | Set the value of a field |
$unset | Remove a field |
$inc | Increment a numeric field |
$push | Add an item to an array |
$pull | Remove an item from an array |
$rename | Rename a field |
4. Delete — Removing Documents
// Delete a single document
db.students.deleteOne({ name: "Divya Rao" })
// Delete multiple documents
db.students.deleteMany({ course: "Mechanical" })
// Delete all documents (keeps the collection)
db.students.deleteMany({})
Common Issue:
updateOne() without $set replaces the entire document rather than merging fields. Always wrap updates in the correct operator.
5. Advanced: upsert and Bulk Writes
// Upsert: insert if no match is found
db.students.updateOne(
{ name: "Ritika Jain" },
{ $set: { age: 21, course: "Data Science" } },
{ upsert: true }
)
// Bulk write for efficiency
db.students.bulkWrite([
{ insertOne: { document: { name: "Kabir", age: 24 } } },
{ updateOne: { filter: { name: "Kabir" }, update: { $set: { age: 25 } } } },
{ deleteOne: { filter: { name: "Kabir" } } }
])
6. CRUD Checklist
- ✅ Comfortable with insertOne/insertMany
- ✅ Know find(), findOne(), and projections
- ✅ Master $set, $inc, $push, $pull operators
- ✅ Understand upsert behavior
- ✅ Use bulkWrite() for batching operations efficiently
Key Takeaway: CRUD operations are the daily bread of database work. Get fluent with update operators especially — they prevent accidental data loss and enable efficient partial updates.
Ready to master MongoDB?
Build real-world MongoDB-powered applications with hands-on projects, mentor-led sessions, and placement support.