MongoDB — Updating Arrays in Documents
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.
| Operator | Purpose | Example |
|---|---|---|
$push | Appends an item to the end of an array | { $push: { tags: "mongodb" } } |
$addToSet | Appends an item ONLY if it does not exist (prevents duplicates) | { $addToSet: { tags: "nodejs" } } |
$pull | Removes all items matching a query condition | { $pull: { tags: "deprecated" } } |
$pop | Removes 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 } }] }
);