Updating and deleting
Updates in MongoDB are powerful: instead of replacing whole documents, you describe changes with update operators like $set and $inc. The server applies them atomically to each document.
updateOne and updateMany
Both take a filter (which documents) and an update (what to change):
The result tells you how many documents matched and how many were actually modified. updateMany changes every match:
⚠️ Forgetting the operator is a classic mistake.
updateOne({…}, { price: 5 })is rejected by mongosh because it would replace the whole document. Try it:
The update operators
| Operator | Does | Example |
|---|---|---|
$set |
Set fields (creates them if missing) | { $set: { status: 'shipped' } } |
$unset |
Remove fields | { $unset: { onSale: '' } } |
$inc |
Add to a number (use negative to subtract) | { $inc: { stock: -1 } } |
$mul |
Multiply a number | { $mul: { price: 1.1 } } |
$rename |
Rename a field | { $rename: { qty: 'quantity' } } |
$min / $max |
Update only if smaller / larger | { $max: { highScore: 950 } } |
$currentDate |
Set to the current date | { $currentDate: { updatedAt: true } } |
$inc is atomic: if two requests run $inc: { stock: -1 } at the same moment, both decrements count. Reading a value in your app, changing it and writing it back can lose updates.
Updating arrays
| Operator | Does |
|---|---|
$push |
Append an element ($each for several) |
$addToSet |
Append only if not already present |
$pull |
Remove elements matching a value or condition |
$pop |
Remove the first (-1) or last (1) element |
Updating one element: the $ and $[] operators
Upserts
With { upsert: true }, if nothing matches, MongoDB inserts a new document built from the filter plus the update. $setOnInsert sets fields only when inserting:
The first call inserted (see upsertedCount: 1); the second matched and incremented.
Replacing a document
replaceOne swaps the whole document for a new one (keeping _id):
Every field not in the replacement is gone. Use $set unless you really mean to replace everything.
Find and modify in one step
findOneAndUpdate updates a document and returns it, atomically. That's perfect for "claim the next job" or "get the next invoice number":
Deleting
⚠️
deleteMany({})deletes every document in the collection. Always run the same filter withfind()first to see what you're about to delete.
Many apps never truly delete important data. Instead they soft delete: $set: { deletedAt: new Date() }, and filter those out in queries.
Practice
- Give every product in the
Kitchencategory a 15% discount with$mul. - Add the tag
'loyal'to every customer who has the'vip'tag, without creating duplicates. - Upsert a document into
settingsfor{ userId: 7 }that setstheme: 'dark', and run it twice. - Delete all orders with status
'cancelled', checking withfindfirst.
1.What does { $inc: { stock: -2 } } do?
2.What is the difference between $push and $addToSet?
3.What does { upsert: true } do when no document matches the filter?