1. Overview
MongoDB provides three main update methods:
-
updateOne(filter, update, options) → updates the first matching document.
-
updateMany(filter, update, options) → updates all matching documents.
-
replaceOne(filter, replacement, options) → replaces an entire document.
All updates are performed in-place (only the specified fields are modified) unless you use replaceOne.
2. Update Operators
Updates use operators to specify how documents should change.
Common Update Operators:
-
$set → set a field value
-
$unset → remove a field
-
$inc → increment/decrement a number
-
$mul → multiply a field
-
$rename → rename a field
-
$push → append to an array
-
$addToSet → append only if not already present
-
$pull → remove from an array
-
$pop → remove first/last element of an array
3. Examples
a) Update One Document
db.users.updateOne(
{ name: "Alice" }, // filter
{ $set: { age: 26 } } // update
)
b) Update Multiple Documents
db.users.updateMany(
{ age: { $lt: 25 } },
{ $set: { status: "young" } }
)
c) Increment a Value
db.users.updateOne(
{ name: "Bob" },
{ $inc: { loginCount: 1 } }
)
d) Remove a Field
db.users.updateOne(
{ name: "Charlie" },
{ $unset: { email: "" } }
)
e) Array Updates
db.users.updateOne(
{ name: "Alice" },
{ $push: { hobbies: "cycling" } }
)
db.users.updateOne(
{ name: "Alice" },
{ $pull: { hobbies: "reading" } }
)
f) Replace Entire Document
db.users.replaceOne(
{ name: "David" },
{ name: "David", age: 30, country: "USA" }
)
4. Options
Example:
db.users.updateOne(
{ name: "Eve" },
{ $set: { age: 29 } },
{ upsert: true }
)
5. Verify Updates
Check updated documents:
db.users.find({ name: "Alice" })