07 / 19

How do we update arrays in the MongoDB documents?

MongoDB provides a rich set of positional operators and array-specific operators to update elements within arrays, from modifying the first match to updating all elements or only those meeting specific filter conditions

Array Update Operators Overview, These operators can be combined with modifiers like `$each` to add multiple items, `$position` to specify insertion location, and `$sort` to order array elements during updates.
  1. 1

    $push operator adds elements to an array

  2. 2

    $pull removes elements that match a condition

  3. 3

    $pop removes the first or last element

  4. 4

    $addToSet ensures uniqueness for adding elements only if they don't already exist

Basic Array Modification Examples
Positional Operators for Element Updates For updating specific elements within an array
  1. 1

    $ updates the first element matching the query condition

  2. 2

    $[] updates all elements in the array

  3. 3

    $[<identifier>] updates elements that match an arrayFilters condition

Using the $ Operator (First Match)
Using the $[] Operator (All Elements)
Using $[<identifier>] with arrayFilters (Conditional Updates)
Advanced Array Manipulation with Modifiers
  1. 1

    $each modifier allows adding multiple items with $push or $addToSet.

  2. 2

    $position modifier controls where elements are inserted, with zero-based indexing.

  3. 3

    $slice modifier limits array size, and $sort orders elements during updates

Advanced Array Operations
Important Considerations
  1. 1

    $ operator restrictions: The $ operator cannot be used with upsert operations (inserts will treat $ as a field name). It also cannot be used with queries that traverse multiple nested arrays [citation:9].

  2. 2

    $ operator with $unset: When used with $unset, the $ operator sets the matching element to null rather than removing it from the array [citation:9].

  3. 3

    Multiple array matches: Using $ with queries that filter on multiple array fields can produce ambiguous results. Use $[<identifier>] with arrayFilters for clearer behavior [citation:9].

  4. 4

    $pullAll limitations: For arrays containing objects, $pullAll may not work as expected due to object comparison semantics. Use $pull with specific query conditions instead [citation:8].

  5. 5

    Upsert with positional operators: When using upsert, the query must include an exact equality match on the array field for positional operators to work correctly during insert [citation:3].