MongoDB Update Operators and Array Patterns

Use $set, $unset, $inc, $push, $addToSet, positional updates, and arrayFilters for real-world MongoDB mutations.

View
StandardDetailedCompact
Export
Copy the compact sheet, download it, or print it.
Download
`D` dense toggle · `C` copy all
## Field update operators
Increment a numeric field
db.posts.updateOne({ _id: 1 }, { $inc: { views: 1 } })

# Increase a counter with `$inc`.

Remove a field
db.users.updateMany({ legacy_flag: { $exists: true } }, { $unset: { legacy_flag: "" } })

# Delete one or more fields from matched documents.

Rename a field
db.users.updateMany({}, { $rename: { fullname: "full_name" } })

# Change a field name in-place.

Stamp an update time
db.users.updateOne({ _id: 1 }, { $currentDate: { updated_at: true } })

# Set a field to the current date.

## Arrays and positional updates
Append to an array
db.users.updateOne({ _id: 1 }, { $push: { tags: "beta" } })

# Push one item onto an array field.

Append only if missing
db.users.updateOne({ _id: 1 }, { $addToSet: { tags: "beta" } })

# Use `$addToSet` to avoid duplicates.

Remove array values
db.users.updateOne({ _id: 1 }, { $pull: { tags: "beta" } })

# Delete matching values from an array.

Update the first matching array element
db.orders.updateOne({ _id: 1, "items.sku": "A100" }, { $set: { "items.$.qty": 3 } })

# Use the positional `$` operator.

Target specific nested elements with arrayFilters
db.orders.updateOne(
  { _id: 1 },
  { $set: { "items.$[line].discounted": true } },
  { arrayFilters: [{ "line.qty": { $gte: 5 } }] }
)

# Update matching array elements with named filters.

Recommended next

No recommendations yet.