MongoDB Update
What Is Update?
MongoDB updates modify existing documents in place. updateOne() changes the first matching document, updateMany() changes every match, and replaceOne() swaps the whole document (keeping only _id). The change itself is described with update operators such as $set, $unset, $inc, $push, and $pull, so you change only the fields you name.
Why It Matters
| Reason | Benefit |
|---|---|
| Targeted changes | Operators modify only the named fields, so you do not have to read and rewrite the whole document. |
| Atomic per document | An update to one document is atomic, so $inc on a counter is safe under concurrency. |
| Array handling built in | $push, $pull, and $addToSet change arrays without client-side loops. |
| Upserts reduce code | A single call can update or create, avoiding a separate existence check. |
How To Use It
- Insert a sample user with fields name, score, and tags.
- Change a field with updateOne({ name: "Mia" }, { $set: { city: "Pune" } }).
- Increase a counter with $inc: { score: 5 }.
- Remove a field using $unset.
- Add and remove array items with $push and $pull.
- Apply a change to many documents using updateMany().
- Replace a full document with replaceOne() and compare the result with $set.
- Read matchedCount, modifiedCount, and upsertedId from the result to verify.
mongosh Examples
db.users.insertOne({ name: "Mia", score: 10, tags: ["new"] })
// Set and increment
db.users.updateOne({ name: "Mia" }, { $set: { city: "Pune" }, $inc: { score: 5 } })
// Remove a field
db.users.updateOne({ name: "Mia" }, { $unset: { city: "" } })
// Arrays
db.users.updateOne({ name: "Mia" }, { $push: { tags: "vip" } })
db.users.updateOne({ name: "Mia" }, { $addToSet: { tags: "vip" } })
db.users.updateOne({ name: "Mia" }, { $pull: { tags: "new" } })
// Many documents
db.users.updateMany({ score: { $lt: 20 } }, { $set: { level: "starter" } })
// Upsert
db.users.updateOne({ name: "Leo" }, { $setOnInsert: { score: 0 } }, { upsert: true })
// Replace everything except _id
db.users.replaceOne({ name: "Leo" }, { name: "Leo", score: 50, level: "pro" }) Edge Cases & Pitfalls
replaceOne drops other fields
Any field not in the replacement document is lost. Use $set to change only some fields.
Operators cannot conflict
You cannot apply two operators to the same field path in one update, such as $set and $inc on score.
$push can duplicate
$push always appends, even when the value exists. Use $addToSet for uniqueness.
Type errors
$inc on a non-numeric field raises an error. Make sure the field is a number first.
Cheat Sheet
| Topic | Detail |
|---|---|
| $set | Set or add a field value |
| $unset | Remove a field: { $unset: { field: "" } } |
| $inc | Add (or subtract with a negative) a number |
| $mul | Multiply a numeric field |
| $rename | Rename a field |
| $push | Append a value to an array |
| $addToSet | Append to an array only if not already present |
| $pull | Remove array elements that match a condition |
| updateOne / updateMany | Apply operators to one or all matches |
| replaceOne | Replace the entire document except _id |
Key Takeaways
Use $set for fields, $inc for counters, $push/$pull for arrays. Without an operator, the update is rejected; use replaceOne() for full replacement.
Frequently Asked Questions
What is the difference between updateOne and updateMany?
updateOne modifies the first matching document. updateMany modifies all matching documents.
How is replaceOne different from updateOne with $set?
replaceOne swaps the entire document except _id. $set changes only the listed fields and leaves everything else alone.
How do I remove a field?
Use $unset with the field name, for example { $unset: { city: "" } }.
How do I add an item to an array only once?
Use $addToSet. It appends the value only if it is not already in the array.
What does upsert do?
With { upsert: true }, MongoDB inserts a new document when the filter matches nothing. $setOnInsert sets fields only in that case.
What do matchedCount and modifiedCount mean?
matchedCount is the number of documents the filter matched. modifiedCount is how many actually changed; setting a field to its current value does not count.
Next: MongoDB Arrays
Continue the MongoDB learning path.
CODETOFUN NEWS
Stay Ahead in Tech
Get the latest IT news, programming updates, and technology trends directly on your phone.
Your daily dose of tech, straight to your feed.
8 people found this page helpful
