Skip to content
Tutorials Center
My learning

Topics

Lesson 22 of 70 ยท CRUD: update and delete

Updating Arrays

Change MongoDB arrays in place with $push, $pull, $addToSet, $pop, $each, $position and $slice, then update single elements with $, $[] and $[id].

Arrays are where MongoDB documents get their power, and where updates get interesting. A document can hold its tags, its cart lines, its last ten log entries. You rarely want to replace a whole array just to add one element, and you often need to change one element inside an array of subdocuments without touching its neighbors. MongoDB has operators for both jobs.

This lesson has two halves. First the operators that change an array's contents: $push, $addToSet, $pull, $pop and the modifiers $each, $position and $slice. Then the operators that address elements: the positional $, the all-elements $[] and the filtered $[identifier]. You should know updateOne, updateMany and result counts from Updating Documents. Plain code blocks are real mongosh commands that cannot run on the site. The TryIts use the site's practice engine, a JavaScript stand-in that applies these operators to arrays of plain objects. It follows MongoDB's rules for the operators shown here, but it has no indexes, no concurrency and no atomic rollback.

Changing array contents

$push Append an element, or many with $each.
$addToSet Add only if it is not there yet.
$pull Remove every element that matches.
$pop Remove the first or the last element.
1 / 2

$push, $each, $position and $slice

$push appends one value to an array, and creates the array if the field does not exist yet. To add several values at once, wrap them in $each; without $each, an array you push becomes one element that is itself an array. Two optional modifiers sit next to $each:

  • $position: n inserts at index n instead of the end (negative values count from the end).
  • $slice: n trims the array after the insert: a positive n keeps the first n elements, a negative n keeps the last n, and 0 empties it.

$push with a negative $slice is the standard "keep only the latest N entries" pattern, for example the ten most recent searches. A third modifier, $sort, is applied before $slice, which gives you a "top N" list. That one is real MongoDB and cannot run here:

JavaScript
db.games.updateOne(
  { _id: "ana" },
  { $push: { scores: { $each: [{ pts: 88 }], $sort: { pts: -1 }, $slice: 3 } } }
)

$addToSet, $pull and $pop

$addToSet adds a value only if an equal element is not already present, so it keeps an array free of duplicates (a "set"). It compares whole values; for subdocuments, the fields must match exactly and in the same order. $pull removes all elements that match a condition. The condition can be a plain value, an operator expression such as { $gte: 40 } for scalar arrays, or a filter on subdocuments, such as { status: "packed" }, which is applied to each element as if it were a document. $pop removes one element from an end: 1 removes the last, -1 removes the first. For removing several exact values there is also $pullAll: { tags: ["a", "b"] }.

JS Push, set, pull and pop

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Follow the array through the steps. The second $addToSet is the interesting pair: adding "js" reports modifiedCount: 0 because it is already there, adding "go" modifies the document. The $slice: -3 keeps [30, 40, 50] after pushing 40 and 50 onto [10, 20, 30], which is exactly the "latest three" pattern. Do remember that arrays that only ever grow are a design smell: a document is limited to 16 MB, and long arrays are slow to update. Schema Design Patterns shows the subset and bucket patterns for that.

Updating one element: the positional $

Often you need to change a single element inside an array of subdocuments, such as marking one cart line as packed. Dot notation can address an element by its index ("items.1.status"), but you usually do not know the index. The positional operator $ is a placeholder for "the first element that matched my filter":

JavaScript
db.orders.updateOne(
  { _id: 1, "items.sku": "ink" },
  { $set: { "items.$.status": "packed" } }
)

Rules to remember: the array must appear in the filter, because MongoDB takes the position from the filter match; it updates only the first matching element; and when the filter has several conditions on the array, use $elemMatch so they refer to the same element (see Array Query Operators). Without a matching array condition in the filter you get an error.

All elements and filtered elements: $[] and $[identifier]

To change every element, use $[]: { $inc: { "items.$[].qty": 1 } }. To change some elements, name a placeholder inside brackets, such as $[big], and describe it in the arrayFilters option. Filter keys start with the placeholder name, and for an array of plain values the key is the placeholder itself:

JavaScript
db.orders.updateOne(
  { _id: 1 },
  { $set: { "items.$[big].status": "bulk" } },
  { arrayFilters: [{ "big.qty": { $gte: 5 } }] }
)

This is the most flexible option. The filter does not need to mention the array, it can update many elements, and you can use several placeholders in one update (even for nested arrays, as in "a.$[x].b.$[y]").

JS $, $[] and $[id] on an array of subdocuments

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Check the first two steps against each other. With only "items.sku": "pen" in the filter, $ points at the first pen (quantity 1), so that one is marked packed even though a second pen exists. With $elemMatch, $ points at the pen whose quantity is at least 5, and it becomes backorder. After $[] added 1 to every quantity, the $[big] rule found the one element with qty of at least 5 and left the others alone. In the last step the placeholder low stands for each plain number below 60, so both weak scores were raised to 60.

Errors you will meet

Two failures are worth recognizing at once. $push, $addToSet, $pull and $pop all fail on a field that exists but is not an array (a string, a number), and a positional $ fails when the filter does not contain a matching condition on the array. The engine raises MongoDB-style errors for both:

JS Two classic array update errors

Press Run (or Ctrl + Enter) to see the console output here.

No output.

If you need to update documents in several arrays at once, or you want an element to be changed even if it was not matched by the filter, prefer $[identifier] with arrayFilters, which does not depend on the filter at all. And when an array grows without limit, or when you update elements often, ask whether the elements deserve to be separate documents instead; Embedding vs Referencing gives a checklist.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. What is the difference between $push and $addToSet?

    $push always appends, so duplicates are possible. $addToSet checks for an equal element first and does nothing if it exists.
  2. 2. How do you keep only the last 5 elements of an array after pushing new ones?

    A negative $slice keeps the last n elements, so { $each: [...], $slice: -5 } trims the array to the newest five. A positive $slice would keep the first five.
  3. 3. A filter { 'items.sku': 'pen' } is used with $set: { 'items.$.status': 'packed' } on an order with two pens. Which element changes?

    The positional operator stands for the first element that matched the filter. Use $[] or $[id] with arrayFilters to change several elements.
  4. 4. Which syntax changes every element of items where qty is at least 5?

    $[identifier] together with arrayFilters selects elements by a rule. $ touches only the first match and $[] touches all elements.

Summary

  • $push appends (use $each for several values); $position inserts elsewhere; $slice trims, and a negative value keeps the latest elements.
  • $addToSet avoids duplicates, $pull removes every element that matches a value or condition, $pop removes the first (-1) or last (1) element.
  • The positional $ updates the first element matched by the filter, so the array must appear in the filter (use $elemMatch for several conditions).
  • $[] updates all elements; $[id] plus arrayFilters updates the elements that pass a rule.
  • Array operators fail on fields that are not arrays; a missing array is created by $push and $addToSet.
  • Keep arrays bounded: documents are limited to 16 MB.

Next, create-or-update behavior and returning the changed document are covered in Upserts, Replace and findAndModify.