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

Common document mutation operators.

Increment a numeric field

Increase a counter with `$inc`.

javascriptANYmongodbincupdate
javascript
db.posts.updateOne({ _id: 1 }, { $inc: { views: 1 } })

Ideal for counters, sequence-like values, and metrics.

Remove a field

Delete one or more fields from matched documents.

javascriptANYmongodbunsetupdate
javascript
db.users.updateMany({ legacy_flag: { $exists: true } }, { $unset: { legacy_flag: "" } })

`$unset` removes the field from documents instead of setting it to null.

Rename a field

Change a field name in-place.

javascriptANYmongodbrenameschema
javascript
db.users.updateMany({}, { $rename: { fullname: "full_name" } })

Useful during schema evolution.

Stamp an update time

Set a field to the current date.

javascriptANYmongodbcurrentDatetimestamps
javascript
db.users.updateOne({ _id: 1 }, { $currentDate: { updated_at: true } })

A simple way to maintain mutation timestamps from the database side.

Arrays and positional updates

Append, deduplicate, and target nested array elements.

Append to an array

Push one item onto an array field.

javascriptANYmongodbpusharrays
javascript
db.users.updateOne({ _id: 1 }, { $push: { tags: "beta" } })

`$push` appends a value even if it already exists.

Append only if missing

Use `$addToSet` to avoid duplicates.

javascriptANYmongodbaddToSetarrays
javascript
db.users.updateOne({ _id: 1 }, { $addToSet: { tags: "beta" } })

Great for tag or role arrays where uniqueness matters.

Remove array values

Delete matching values from an array.

javascriptANYmongodbpullarrays
javascript
db.users.updateOne({ _id: 1 }, { $pull: { tags: "beta" } })

Useful for cleanup and preference toggles.

Update the first matching array element

Use the positional `$` operator.

javascriptANYmongodbarrayspositional
javascript
db.orders.updateOne({ _id: 1, "items.sku": "A100" }, { $set: { "items.$.qty": 3 } })

The positional operator targets the first matched array element in the query.

Target specific nested elements with arrayFilters

Update matching array elements with named filters.

javascriptANYmongodbarraysarrayFilters
javascript
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.

Recommended next

No recommendations yet.