MongoDB Update Documents
To update documents in MongoDB you pass a filter to choose documents and an update document with operators like $set that describe the change. updateOne changes the first match, updateMany changes all matches.
updateOne with $set
$set changes or adds fields without touching the rest of the document.
db.products.updateOne(
{ name: "Honey" },
{ $set: { stock: 50, price: 12.65 } }
){
acknowledged: true,
insertedId: null,
matchedCount: 1,
modifiedCount: 1,
upsertedCount: 0
}updateMany with $inc
$inc adds to a number (use a negative value to subtract). Here every beverage gets 10 extra units of stock.
db.products.updateMany(
{ category: "Beverages" },
{ $inc: { stock: 10 } }
){ acknowledged: true, insertedId: null, matchedCount: 2, modifiedCount: 2, upsertedCount: 0 }Array Operators: $push, $addToSet, $pull
$push appends to an array, $addToSet appends only if the value is missing, and $pull removes matching values.
db.products.updateOne({ name: "Green Tea" }, { $addToSet: { tags: "organic" } })
db.products.updateOne({ name: "Almonds" }, { $pull: { tags: "organic" } })
db.products.find({ tags: "organic" }, { _id: 0, name: 1, tags: 1 })[
{ name: 'Basmati Rice', tags: [ 'organic' ] },
{ name: 'Green Tea', tags: [ 'organic' ] }
]Other Update Operators
- $unset removes a field
- $rename renames a field
- $mul multiplies a number
- $min / $max update only if the new value is lower / higher
- $currentDate sets a field to the current date
Upsert and replaceOne
With upsert: true, MongoDB inserts a new document when nothing matches. replaceOne swaps the whole document (except _id) for a new one.
db.products.updateOne(
{ name: "Wheat Flour" },
{ $set: { category: "Grains", price: 8, stock: 200 } },
{ upsert: true }
){
acknowledged: true,
insertedId: ObjectId('6720a7a9c2b9e81d4f3a1b0b'),
matchedCount: 0,
modifiedCount: 0,
upsertedCount: 1
}Frequently asked questions
What is the difference between updateOne and replaceOne?
updateOne applies operators like $set to change specific fields. replaceOne replaces the entire document with the one you pass, removing any fields you leave out.
How do I update a nested field in MongoDB?
Use dot notation: { $set: { "address.city": "Lahore" } }. Setting address: {...} instead would replace the whole embedded document.
How do I update a specific element in an array?
Use the positional operator: filter on the element, then $set: { "items.$.qty": 5 }. For several elements use arrayFilters with $[name].