Chapter 8: MongoDB mongosh Update
MongoDB mongosh Update — the U in CRUD.
This is how you modify existing documents without deleting and re-inserting everything.
1. The Two Main Update Methods in mongosh (2026 Standard)
| Method | What it does | How many documents updated? | Most common return value (acknowledged + …) | Best for |
|---|---|---|---|---|
| db.collection.updateOne(filter, update, options) | Updates the first matching document | At most 1 | { acknowledged: true, matchedCount: 1, modifiedCount: 1, upsertedId: ? } | Precise changes: user profile, order status, single wish edit |
| db.collection.updateMany(filter, update, options) | Updates all matching documents | 0 to many | { acknowledged: true, matchedCount: N, modifiedCount: N } | Bulk fixes: increase likes for all posts, mark old records, apply raises |
Important teacher notes:
- Both methods do NOT replace the whole document by default — they modify fields using update operators like $set, $inc, $push, etc.
- If no document matches → nothing happens (unless you use upsert: true).
- Always use update operators in the second argument (the update part) — plain { name: “NewName” } replaces the entire document (replacement mode, not recommended for most cases).
Old method warning: db.collection.update() is still there but deprecated in favor of updateOne / updateMany since ~2015–2016. Use the new ones.
2. Most Important Update Operators (You’ll Use These Daily)
| Operator | What it does | Example Use Case | Syntax Snippet |
|---|---|---|---|
| $set | Set / create field to new value | Change message, update price, add status | { $set: { message: “Updated love note ❤️” } } |
| $unset | Remove field completely | Delete old field like oldPhone | { $unset: { oldField: “” } } |
| $inc | Increment/decrement number | Add likes, increase salary, age +1 | { $inc: { likes: 1, views: -5 } } |
| $push | Add element to array | Add new comment, hobby, tag | { $push: { hobbies: “dancing” } } |
| $pull | Remove element from array | Remove tag, delete comment | { $pull: { tags: “old” } } |
| $addToSet | Add to array only if not exists | Unique friends list | { $addToSet: { friends: “Priya” } } |
| $currentDate | Set field to current date/time | Update lastModified | { $currentDate: { lastModified: true } } |
| $rename | Rename a field | userName → username | { $rename: { “userName”: “username” } } |
There are many more (array positional $, $min/$max, $mul, etc.) — but these cover ~90% of real-world updates.
3. Hands-on Examples — Using Our valentines2026 Database
Assume we have db.wishes with documents like:
|
0 1 2 3 4 5 6 7 8 9 10 |
[ { "_id": ..., "from": "Rahul", "to": "Priya", "message": "Happy Valentine's...", "rating": 10, "likes": 3 }, { "from": "Amit", "to": "Sneha", "message": "...", "likes": 1 }, { "from": "Priya", "to": "Rahul", "message": "...", "rating": 11, "likes": 5 } ] |
Example 1: updateOne() — Change one specific wish
|
0 1 2 3 4 5 6 7 8 9 |
db.wishes.updateOne( { from: "Rahul", to: "Priya" }, // filter: find this wish { $set: { message: "I love you even more now! ❤️❤️" } } // change only message ) |
Output example:
|
0 1 2 3 4 5 6 7 8 9 10 |
{ acknowledged: true, matchedCount: 1, modifiedCount: 1 } |
→ Only that one document’s message changed.
Example 2: updateMany() — Bulk update (very common)
|
0 1 2 3 4 5 6 7 8 9 10 |
// Give +2 likes to ALL wishes db.wishes.updateMany( {}, // empty filter = all documents { $inc: { likes: 2 } } ) |
|
0 1 2 3 4 5 6 7 8 9 10 |
// Mark all wishes with rating >=10 as "popular" db.wishes.updateMany( { rating: { $gte: 10 } }, { $set: { isPopular: true }, $currentDate: { lastUpdated: true } } ) |
Example 3: Add to array field
|
0 1 2 3 4 5 6 7 8 9 |
db.wishes.updateOne( { from: "Rahul" }, { $push: { gifts: { name: "Rose bouquet", date: new Date() } } } ) |
→ Creates gifts array if missing, then appends.
Example 4: Upsert (Update if exists, Insert if not — magic!)
|
0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 |
db.wishes.updateOne( { from: "NewBoy", to: "NewGirl" }, // probably doesn't exist { $set: { message: "First Valentine wish!", date: new Date(), rating: 5 } }, { upsert: true } // ← the magic option ) |
→ If match → update → If no match → insert new document with the $set fields
Output will show upsertedId if insert happened.
Example 5: Remove fields + rename
|
0 1 2 3 4 5 6 7 8 9 10 11 12 |
db.wishes.updateMany( {}, { $unset: { oldField: "" }, $rename: { "rating": "loveScore" } } ) |
4. Quick Cheat Sheet Table
| Goal | Method | Filter example | Update example | Options often used |
|---|---|---|---|---|
| Change one field in one doc | updateOne | { _id: ObjectId(…) } | { $set: { status: “read” } } | — |
| Increase number everywhere | updateMany | {} | { $inc: { views: 1 } } | — |
| Add item to array (unique) | updateOne / Many | { user: “Rahul” } | { $addToSet: { tags: “romantic” } } | — |
| Update or create if missing | updateOne | { email: “rahul@hyd.in” } | { $set: { lastLogin: new Date() } } | { upsert: true } |
| Touch timestamp on update | — | — | { $currentDate: { updatedAt: true } } | — |
| Bulk safe write (majority confirmed) | — | — | — | { writeConcern: { w: “majority” } } |
5. Mini Exercise — Try Right Now!
- use valentines2026
- Find your earlier wish (e.g., from “Rahul”)
- Update its message to something sweeter
- Add 3 more likes to all wishes (updateMany + $inc)
- Add a new field sentVia: “MongoDB love” to one wish
- Check with find().pretty()
Understood beta? Updating is where data starts feeling alive — it grows, changes, gets better.
Next class — what next?
- Delete (the D in CRUD — remove old broken hearts)?
- ReplaceOne vs update (when to replace whole doc)?
- Array operators deep dive ($push with $each, $sort, positional $)?
- Or start combining CRUD in a tiny “Valentine Message Board” mini-app?
Tell me — class is yours! 🚀❤️
Any doubt in update? Ask freely — we’re in this together! 😄
