CRUD: Update
Update operations let you modify existing documents without deleting and recreating them. MongoDB provides flexible update operators that allow you to change specific fields, add new ones, or even transform data—all atomically.
Understanding Atomic Updates
One of MongoDB’s strengths is atomic single-document operations. When you update a document:
- The update happens completely or not at all
- No other operation can see the document in a half-updated state
- Multiple fields can be changed in a single operation
This is crucial for data consistency. For example, when transferring money between accounts in a single document, both the debit and credit happen atomically.
Update Philosophy: Operators vs. Replacement
MongoDB offers two approaches to updates:
| Approach | Use Case | Risk Level |
|---|
Update operators ($set, $inc, etc.) | Modify specific fields | Low—preserves other fields |
| Document replacement | Replace entire document | High—can accidentally lose fields |
Always prefer update operators over document replacement. Replacing a document without including all existing fields will permanently delete those fields.
Update Methods
Update operations modify existing documents in a collection.
updateOne()
Updates the first document that matches the filter.
db.users.updateOne(
{ name: "Alice" }, // Filter
{ $set: { age: 26 } } // Update Action
)
updateMany()
Updates all documents that match the filter.
db.users.updateMany(
{ age: { $lt: 18 } },
{ $set: { status: "minor" } }
)
replaceOne()
Replaces the entire document (except _id) with a new document.
db.users.replaceOne(
{ name: "Bob" },
{ name: "Bob Smith", role: "admin" }
)
Update Operators
$set: Sets the value of a field in a document.
$unset: Removes the specified field from a document.
$inc: Increments the value of the field by the specified amount.
$push: Appends a value to an array.
$pull: Removes a specified value from an array.
Examples:
// Increment age by 1
db.users.updateOne(
{ name: "Alice" },
{ $inc: { age: 1 } }
)
// Add "swimming" to hobbies array
db.users.updateOne(
{ name: "Alice" },
{ $push: { hobbies: "swimming" } }
)
Upsert
If upsert: true is specified, the operation creates a new document if no documents match the filter.
db.users.updateOne(
{ name: "David" },
{ $set: { age: 40 } },
{ upsert: true }
)
Summary
- Use
updateOne() and updateMany().
- Always use Update Operators (like
$set, $inc) unless you want to replace the whole document.
- Upsert creates a document if it doesn’t exist.