MongoDb - MongoDB update operations
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
)
-
Finds the first user named Alice and sets
age = 26
.
b) Update Multiple Documents
db.users.updateMany(
{ age: { $lt: 25 } },
{ $set: { status: "young" } }
)
-
Adds
status: "young"
to all users younger than 25.
c) Increment a Value
db.users.updateOne(
{ name: "Bob" },
{ $inc: { loginCount: 1 } }
)
-
Increases Bob’s
loginCount
by 1.
d) Remove a Field
db.users.updateOne(
{ name: "Charlie" },
{ $unset: { email: "" } }
)
-
Removes the
email
field from Charlie’s document.
e) Array Updates
db.users.updateOne(
{ name: "Alice" },
{ $push: { hobbies: "cycling" } }
)
db.users.updateOne(
{ name: "Alice" },
{ $pull: { hobbies: "reading" } }
)
-
$push
adds"cycling"
to Alice’shobbies
array. -
$pull
removes"reading"
from the array.
f) Replace Entire Document
db.users.replaceOne(
{ name: "David" },
{ name: "David", age: 30, country: "USA" }
)
-
Replaces David’s whole document with the new one.
-
⚠️ Any fields not included are lost.
4. Options
-
upsert: true
→ Insert a new document if none matches.
Example:
db.users.updateOne(
{ name: "Eve" },
{ $set: { age: 29 } },
{ upsert: true }
)
-
If Eve exists → update her age.
-
If not → insert a new document
{ name: "Eve", age: 29 }
.
5. Verify Updates
Check updated documents:
db.users.find({ name: "Alice" })