Update Operators
Precisely describe document changes using $set, $inc, $unset, $push, $pull, and other update operators.
Field Update Operators
| Operator | Purpose | Example |
|---|---|---|
| $set | Sets a field to a specific value (creates it if absent) | { $set: { age: 29 } } |
| $unset | Removes a field entirely | { $unset: { middleName: "" } } |
| $rename | Renames a field | { $rename: { "oldName": "newName" } } |
db.users.updateOne( { email: "ada@example.com" }, { $set: { age: 29, verified: true }, $unset: { tempToken: "" } },);$inc for Numeric Fields
$inc increments (or decrements, with a negative value) a numeric field atomically — safer than reading a value, adding to it in application code, and writing it back, which can race with concurrent updates.
db.posts.updateOne({ _id: postId }, { $inc: { views: 1 } }); // increment by 1db.products.updateOne({ _id: productId }, { $inc: { stock: -1 } }); // decrement by 1Array Update Operators
| Operator | Purpose |
|---|---|
| $push | Appends a value to an array |
| $pull | Removes all matching values from an array |
| $pop | Removes the first (-1) or last (1) element of an array |
| $addToSet | Adds a value only if it isn't already present |
db.posts.updateOne({ _id: postId }, { $push: { tags: "mongodb" } });db.posts.updateOne({ _id: postId }, { $pull: { tags: "deprecated" } });db.posts.updateOne({ _id: postId }, { $pop: { comments: 1 } }); // remove the last comment$addToSet vs $push
$push always appends, even if the value already exists, potentially creating duplicates. $addToSet only adds the value if it's not already present, effectively treating the array like a set.
db.users.updateOne({ _id: userId }, { $addToSet: { roles: "admin" } });// Running this twice results in "admin" appearing only onceEvery update operator applies atomically to a single document — this is what makes $inc safe under concurrent writes without extra locking logic in your application code.
Common Beginner Mistakes
Use $addToSet instead whenever an array field should behave like a unique set rather than an ordered list allowing repeats.
This is a race condition under concurrent requests — use $inc to perform the increment atomically on the database side instead.
FAQs
Yes — a single update document commonly combines $set, $inc, and array operators together, all applied atomically as one operation.
No — the value ("" in these examples) is ignored; only the key matters for $unset.
Summary
Update operators like $set, $inc, $push, and $addToSet let you precisely and atomically describe exactly what should change on a document. Next, you'll learn how to remove documents entirely.