MongoDB update operators modify selected fields without replacing the complete document. $set assigns a value, $unset removes a field, $inc changes a numeric value, and array operators modify array membership. A single-document update is atomic, but a read followed by a separate write can still race.
Updating a user display name should not overwrite preferences, addresses, or audit fields. Operators such as $set and $inc avoid whole-document replacement.
Arrays need different operators depending on intent. Appending, preventing duplicates, removing values, and updating embedded items are separate operations.
Upsert is useful for idempotent writes, but dangerous with vague filters. Use a unique key in the filter and $setOnInsert for creation-only fields.
Include identity and any concurrency condition in the update filter, then inspect matchedCount and modifiedCount. Dot notation targets nested fields without replacing the entire parent object. Validate operator and field choices on the server instead of accepting an arbitrary update document from a client.
$push can create duplicates while $addToSet enforces set-like membership for exact values. Use arrayFilters for selected nested array elements and test the filter carefully. Multi-document consistency requires a transaction only when the data model cannot keep the invariant in one document.
db.products.updateOne(
{ sku: "KB-101", stock: { $gte: 1 } },
{ $inc: { stock: -1, reserved: 1 }, $currentDate: { updatedAt: true } }
)
An array filter changes the intended line item without replacing the full array.
db.orders.updateOne(
{ _id: 42 },
{ $set: { 'items.$[item].status': 'packed' } },
{ arrayFilters: [{ 'item.sku': 'BK-7', 'item.status': 'paid' }] }
)
Only the paid BK-7 item becomes packed.
No. The filter chooses documents; update operators define the change.
$inc is atomic for a single document and avoids read-modify-write races.
Practice, interview questions, and compiler links for MongoDB Update Operators.
Finish the concept here, then reinforce it with hands-on coding, interview prep, or a tool that matches the topic.
Explore 500+ free tutorials across 20+ languages and frameworks.
Fresh tutorials, interview guides, and coding practice in your inbox.