Chapter 11: MongoDB Update Operators
MongoDB Update Operators — the $ prefixed tools you put in the second argument of updateOne(), updateMany(), findOneAndUpdate(), replaceOne() (sometimes), and even aggregation $merge/$set stages.
These operators are what make updates atomic, efficient, and expressive — MongoDB modifies only what you ask for, without you having to read → change → write the whole document yourself.
1. Big Picture – Categories of Update Operators (2026)
MongoDB groups them roughly like this (from official docs):
| Category | Purpose | Most popular operators | Daily usage frequency |
|---|---|---|---|
| Field Update | Change / create / remove scalar fields | $set, $unset, $inc, $mul, $rename, $currentDate, $min, $max | ★★★★★ (almost every update) |
| Array Update | Manipulate arrays (append, remove, reorder, etc.) | $push, $pull, $addToSet, $pop, $pullAll | ★★★★☆ (very common) |
| Array Filters / Positional | Target specific array elements during update | $[<identifier>], $[], $[<condition>] | ★★★☆☆ (advanced but powerful) |
| Bitwise | Bit-level operations on integers | $bit | ★☆☆☆☆ (rare) |
| Others | Less common (e.g., bulkWrite helpers) | — | — |
Key rules teacher always repeats:
- Update operators must be inside an object like { $set: {…}, $inc: {…} }
- You can combine multiple operators in one update (they apply in order)
- Fields are processed in lexicographic order (since MongoDB 5.0+), but numeric dotted paths sort numerically
- Use dot notation for nested fields: “profile.age”: 25
2. Hands-on – Most Important Update Operators (with examples)
Let’s use our familiar school2026 database again:
|
0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 |
use school2026 db.students.insertMany([ { _id: 1, name: "Rahul", age: 16, city: "Hyderabad", marks: { math: 92, science: 85, english: 78 }, hobbies: ["cricket", "coding"], likes: 12, lastActive: ISODate("2026-02-10"), tags: ["active", "good_math"] }, { _id: 2, name: "Priya", age: 15, city: "Secunderabad", marks: { math: 95 }, hobbies: ["dance"], likes: 8 } ]) |
A. Field Update Operators (Daily Bread)
- $set — Set / create field (most used operator ever)
|
0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
db.students.updateOne( { _id: 1 }, { $set: { "marks.english": 88, // nested status: "promoted", // new field "profile.bio": "Loves MongoDB ❤️" // creates nested object } } ) |
- $unset — Remove field completely
|
0 1 2 3 4 5 6 7 8 9 |
db.students.updateMany( { city: "Hyderabad" }, { $unset: { "marks.english": "", tempField: "" } } // value doesn't matter ) |
- $inc — Increment / decrement numbers
|
0 1 2 3 4 5 6 7 8 9 10 11 12 13 |
// Give +5 math marks & +3 likes to everyone db.students.updateMany( {}, { $inc: { "marks.math": 5, likes: 3 } } ) // Decrease age by 1 (birthday rollback? 😄) db.students.updateOne({ _id: 1 }, { $inc: { age: -1 } }) |
- $currentDate — Set to now (very useful for timestamps)
|
0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
db.students.updateOne( { _id: 1 }, { $currentDate: { lastActive: true, // Date type lastActiveTS: { $type: "timestamp" } // Timestamp type } } ) |
- $rename — Change field name
|
0 1 2 3 4 5 6 7 8 9 |
db.students.updateMany( {}, { $rename: { "marks.math": "marks.mathematics" } } ) |
- $min / $max — Set only if smaller/larger
|
0 1 2 3 4 5 6 7 8 9 10 |
// Update "lowestScore" only if new value is smaller db.students.updateOne( { _id: 1 }, { $min: { lowestScore: 68 } } ) |
B. Array Update Operators (Where MongoDB shines)
- $push — Append to array
|
0 1 2 3 4 5 6 7 8 9 |
db.students.updateOne( { _id: 1 }, { $push: { hobbies: "guitar" } } // simple append ) |
With modifiers (very powerful):
|
0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 |
db.students.updateOne( { _id: 1 }, { $push: { activities: { $each: [ "quiz", "project" ], $sort: { score: -1 }, // optional $position: 0 // insert at beginning } } } ) |
- $addToSet — Add only if not already present
|
0 1 2 3 4 5 6 7 8 9 |
db.students.updateMany( {}, { $addToSet: { tags: "valentineLearner" } } ) |
- $pull — Remove matching elements
|
0 1 2 3 4 5 6 7 8 9 |
db.students.updateOne( { _id: 1 }, { $pull: { hobbies: "coding" } } // remove exact value ) |
|
0 1 2 3 4 5 6 7 8 9 10 |
// Remove objects that match condition db.students.updateOne( { _id: 1 }, { $pull: { grades: { subject: "english", score: { $lt: 80 } } } } ) |
- $pop — Remove first/last element
|
0 1 2 3 4 5 6 7 8 9 |
db.students.updateOne( { _id: 1 }, { $pop: { hobbies: 1 } } // 1 = last, -1 = first ) |
C. Positional / Filtered Positional Updates (Advanced but very useful)
|
0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 |
// Update first matching array element db.students.updateOne( { _id: 1, "grades.subject": "math" }, { $set: { "grades.$.score": 98 } } // $ = positional operator ) // Update all matching (filtered positional – MongoDB 3.6+) db.students.updateOne( { _id: 1 }, { $set: { "grades.$[elem].score": 100 } }, { arrayFilters: [ { "elem.subject": "math" } ] } ) |
3. Quick Summary Table – Your Go-To Cheat Sheet
| Operator | What it does (one-liner) | Typical Example Use Case | Combine with others? |
|---|---|---|---|
| $set | Set value (create if missing) | Update name, status, nested score | Yes |
| $unset | Remove field | Clean old/temporary fields | Yes |
| $inc | + / – number | Likes, views, points, counters | Yes |
| $push | Append to array | Add comment, tag, log entry | Yes (with $each) |
| $addToSet | Append only if unique | Unique friends, categories, roles | Yes |
| $pull | Remove from array | Delete tag, remove invalid entry | Yes |
| $currentDate | Set to current date/timestamp | updatedAt, lastLogin | Yes |
| $rename | Rename field | Fix naming mistakes | Yes |
| $min / $max | Keep smallest / largest value | Track min/max price, score | Yes |
4. Mini Exercise – Try Right Now in mongosh!
- Give +10 likes and update lastActive to now for Rahul
- Add “mongodb” to Rahul’s hobbies only if not present
- Remove “cricket” from hobbies of all students
- Rename marks.math → marks.mathematics everywhere
- Check results with find().pretty()
Understood beta? These operators are what make MongoDB updates feel surgical — precise, safe, and fast.
Next class — what do you want?
- Deep dive into arrayFilters + positional $ operators?
- bulkWrite() for mixed insert/update/delete?
- findOneAndUpdate() (return before/after)?
- Or start a small project combining all CRUD + operators?
Tell me — we’re building real skills here! 🚀❤️
Any operator still confusing? Ask right away — we’ll practice together! 😄
