In MongoDB, modifying documents requires atomic update operators. Replacing an entire document accidentally is an infamous beginner mistake. MongoDB provides precise atomic field modifiers like $set, $inc, $push, and $pull to update documents safely.
updateOne() vs updateMany()updateOne(filter, update, options): Updates the first matching document.updateMany(filter, update, options): Updates all documents matching the filter.| Operator | Action | Example |
|---|---|---|
$set | Sets or creates the value of a field | { $set: { price: 2999, 'meta.verified': true } } |
$unset | Deletes a field from the document | { $unset: { temporaryToken: "" } } |
$inc | Increments/decrements a numeric field atomically | { $inc: { views: 1, inventory: -1 } } |
$min / $max | Updates only if the value is less/greater than current | { $max: { highScore: 980 } } |
$currentDate | Sets field to current timestamp or Date | { $currentDate: { updatedAt: true } } |
$push, $pull, $addToSetMongoDB allows modifying array fields directly inside a document without fetching the document into JavaScript memory:
$push: Appends a new item to an array:$addToSet: Adds an item only if it does not already exist in the array (prevents duplicate tags):$pull: Removes all occurrences of matching items from an array:upsert: true)An Upsert is a hybrid operation: if a matching document is found, it is updated; if no document matches the filter, a new document is inserted:
{ price: 1999 } without $set as the update parameter in collection.updateOne()?$addToSet differ from $push when modifying an array field?{ upsert: true } option accomplish in an update operation?Continue learning with hands-on practice, examples, and exercises in the upcoming topic.
Test your understanding of this lesson with 5 questions. Each question has one correct answer.
Practice in live mentor-led sessions with real projects, mock tests, and verifiable certification at MSK Institute.