MongoDB — Updating Arrays in Documents

🍃 MongoDB 7.0+ 🟢 Chapter 21 of 50 📂 Phase 05: Array Updates, Upserts & Deletions 📅 2026 Edition

Master array mutation operations in MongoDB. Learn how to push, pull, deduplicate, and perform conditional positional updates on nested elements.

1Array Update Operators Overview

Arrays in BSON documents require specialized update modifiers because updating an array involves adding, removing, or modifying specific elements within a list.

OperatorPurposeExample
$pushAppends an item to the end of an array{ $push: { tags: "mongodb" } }
$addToSetAppends an item ONLY if it does not exist (prevents duplicates){ $addToSet: { tags: "nodejs" } }
$pullRemoves all items matching a query condition{ $pull: { tags: "deprecated" } }
$popRemoves the first (-1) or last (1) item of an array{ $pop: { logs: 1 } }
2Advanced $push Modifiers ($each, $slice, $sort, $position)

You can combine $push with modifiers to manage array size and ordering atomically:

$push Modifiers Example
// Push multiple items, keep array sorted by score descending, limit to top 5 items
db.leaderboards.updateOne(
  { _id: "game_101" },
  {
    $push: {
      scores: {
        $each: [ { player: "Alex", score: 95 }, { player: "Sam", score: 88 } ],
        $sort: { score: -1 },
        $slice: 5
      }
    }
  }
);
3Positional Update Operators ($, $[], $[elem])
Positional Array Updates
// 1. Positional Operator ($): Updates the FIRST matched array element
db.students.updateOne(
  { _id: 101, "grades.subject": "Math" },
  { $set: { "grades.$.score": 95 } }
);

// 2. All Positional Operator ($[]): Updates ALL array elements
db.products.updateOne(
  { _id: 501 },
  { $inc: { "prices.$[]": 5 } }
);

// 3. Filtered Positional Operator ($[elem]): Updates elements matching arrayFilters
db.students.updateOne(
  { _id: 101 },
  { $set: { "scores.$[elem]": 100 } },
  { arrayFilters: [{ "elem": { $lt: 50 } }] }
);
OC
Written by Our Compiler Technical Editorial Team
Reviewed for accuracy & tested on MongoDB 7.0+ Standards · Last updated August 2026