How do you update documents in MongoDB?
BeginnerHands-onMongoDB
Answer
Short answer
Use updateOne or updateMany with a filter and update operators like $set, $unset, $inc and $push. Use upsert: true to insert the document if nothing matches, and replaceOne to replace a whole document.
Examples
db.orders.updateOne({ _id: ObjectId("...") }, { $set: { status: "SHIPPED", shippedAt: new Date() } })
db.products.updateMany({ category: "phones" }, { $inc: { price: -500 } })
db.customers.updateOne({ email: "[email protected]" }, { $push: { tags: "vip" } })
db.customers.updateOne({ email: "[email protected]" }, { $unset: { tempToken: "" } })
db.counters.updateOne({ _id: "orders" }, { $inc: { seq: 1 } }, { upsert: true })
Operators
| Operator | Does |
|---|---|
$set |
Set field values |
$unset |
Remove a field |
$inc |
Add to a number |
$push / $pull |
Add to / remove from an array |
$addToSet |
Add to an array if not already present |
Watch out
Without an operator, updateOne(filter, { status: "X" }) fails in modern drivers — older shells used to replace the whole document. And an empty filter {} matches every document in updateMany.
What to say in the interview
"updateOne/updateMany with operators like $set, $inc and $push; upsert to insert when nothing matches. I always double-check the filter, because an empty filter in updateMany touches the whole collection."