Updating Arrays

1. Adding to Arrays

OperatorBehavior
$pushAppend element
$push + $eachAppend multiple
$addToSetAppend if not already present
db.users.updateOne({_id: id}, { $push: { tags: "vip" } });

2. Adding Multiple Items

FormEffect
$push: { tags: { $each: ["a","b"] } }Append multiple
$addToSet: { tags: { $each: ["a","b"] } }Unique multi-add
With $sort / $sliceMaintain bounded sorted array

3. Removing Items

OperatorEffect
$pullRemove elements matching condition
$pullAllRemove elements equal to any in list
$popRemove first (-1) or last (1)
db.users.updateMany({}, { $pull: { sessions: { expiresAt: { $lt: new Date() } } } });

4. Removing First or Last

FormEffect
$pop: {tags: 1}Remove last element
$pop: {tags: -1}Remove first element

5. Adding Unique Items

AspectDetail
$addToSetEquality compare entire value (incl. nested docs by exact match)
Subdoc gotcha{a:1,b:2} ≠ {b:2,a:1} for some BSON forms; use canonical field order

6. Updating Array Elements by Position ($)

FormEffect
{"items.$": value}First matched element from query filter
RequiresArray field in filter
db.orders.updateOne(
  { _id: id, "items.sku": "A" },
  { $set: { "items.$.qty": 5 } }
);

7. Updating All Array Elements ($[])

FormEffect
{"scores.$[]": newValue}Update every element
{"scores.$[]": {$mul: 1.1}}Use with operators

8. Using Filtered Positional Operator ($[identifier])

FormEffect
$[elem]Update elements matching arrayFilters entry
arrayFiltersArray of filter docs per identifier
MultipleMultiple identifiers per update allowed
db.classes.updateMany(
  {},
  { $set: { "students.$[s].passed": true } },
  { arrayFilters: [ { "s.grade": { $gte: 70 } } ] }
);

9. Slicing Arrays

FormEffect
$push: { items: { $each: [...], $slice: 100 } }Keep first 100
$slice: -100Keep last 100
Use caseBounded log/activity feed

10. Sorting Array Elements

FormEffect
$push: { items: { $each: [...], $sort: {ts: -1} } }Sort subdocs by field
$sort: 1Sort scalar array ascending

11. Limiting Array Size

PatternForm
Bounded queue$push: {recent: {$each: [x], $slice: -50}}
Top-N by score$each + $sort + $slice

12. Using $pullAll to Remove Multiple

FormEffect
$pullAll: { tags: ["x","y"] }Remove every element equal to any listed value
vs $pull$pullAll uses equality; $pull uses match expression