LearnAI ToolsCareerPractice BuildsPlayContact
Lesson 1617 min read

Update Operators

Precisely describe document changes using $set, $inc, $unset, $push, $pull, and other update operators.

Field Update Operators

OperatorPurposeExample
$setSets a field to a specific value (creates it if absent){ $set: { age: 29 } }
$unsetRemoves a field entirely{ $unset: { middleName: "" } }
$renameRenames 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 1
db.products.updateOne({ _id: productId }, { $inc: { stock: -1 } }); // decrement by 1

Array Update Operators

OperatorPurpose
$pushAppends a value to an array
$pullRemoves all matching values from an array
$popRemoves the first (-1) or last (1) element of an array
$addToSetAdds 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 once
Atomicity Matters

Every 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

Using $push when duplicates aren't wanted

Use $addToSet instead whenever an array field should behave like a unique set rather than an ordered list allowing repeats.

Reading a value in application code, incrementing it, then writing it back

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.

Next Lesson →

Deleting Documents