db.posts.updateOne({ _id: 1 }, { $inc: { views: 1 } })Ideal for counters, sequence-like values, and metrics.
Use $set, $unset, $inc, $push, $addToSet, positional updates, and arrayFilters for real-world MongoDB mutations.
Common document mutation operators.
db.posts.updateOne({ _id: 1 }, { $inc: { views: 1 } })Ideal for counters, sequence-like values, and metrics.
db.users.updateMany({ legacy_flag: { $exists: true } }, { $unset: { legacy_flag: "" } })`$unset` removes the field from documents instead of setting it to null.
db.users.updateMany({}, { $rename: { fullname: "full_name" } })Useful during schema evolution.
db.users.updateOne({ _id: 1 }, { $currentDate: { updated_at: true } })A simple way to maintain mutation timestamps from the database side.
Append, deduplicate, and target nested array elements.
db.users.updateOne({ _id: 1 }, { $push: { tags: "beta" } })`$push` appends a value even if it already exists.
db.users.updateOne({ _id: 1 }, { $addToSet: { tags: "beta" } })Great for tag or role arrays where uniqueness matters.
db.users.updateOne({ _id: 1 }, { $pull: { tags: "beta" } })Useful for cleanup and preference toggles.
db.orders.updateOne({ _id: 1, "items.sku": "A100" }, { $set: { "items.$.qty": 3 } })The positional operator targets the first matched array element in the query.
Update matching array elements with named filters.
db.orders.updateOne(
{ _id: 1 },
{ $set: { "items.$[line].discounted": true } },
{ arrayFilters: [{ "line.qty": { $gte: 5 } }] }
)`arrayFilters` are powerful for targeted nested updates without rewriting the whole array.