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:

JSON

Example 1: updateOne() — Change one specific wish

JavaScript

Output example:

JSON

→ Only that one document’s message changed.

Example 2: updateMany() — Bulk update (very common)

JavaScript
JavaScript

Example 3: Add to array field

JavaScript

→ Creates gifts array if missing, then appends.

Example 4: Upsert (Update if exists, Insert if not — magic!)

JavaScript

→ 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

JavaScript

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!

  1. use valentines2026
  2. Find your earlier wish (e.g., from “Rahul”)
  3. Update its message to something sweeter
  4. Add 3 more likes to all wishes (updateMany + $inc)
  5. Add a new field sentVia: “MongoDB love” to one wish
  6. 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! 😄

You may also like...

Leave a Reply

Your email address will not be published. Required fields are marked *