Updating Arrays
1. Adding to Arrays
| Operator | Behavior |
| $push | Append element |
| $push + $each | Append multiple |
| $addToSet | Append if not already present |
db.users.updateOne({_id: id}, { $push: { tags: "vip" } });
2. Adding Multiple Items
| Form | Effect |
$push: { tags: { $each: ["a","b"] } } | Append multiple |
$addToSet: { tags: { $each: ["a","b"] } } | Unique multi-add |
| With $sort / $slice | Maintain bounded sorted array |
3. Removing Items
| Operator | Effect |
| $pull | Remove elements matching condition |
| $pullAll | Remove elements equal to any in list |
| $pop | Remove first (-1) or last (1) |
db.users.updateMany({}, { $pull: { sessions: { expiresAt: { $lt: new Date() } } } });
4. Removing First or Last
| Form | Effect |
$pop: {tags: 1} | Remove last element |
$pop: {tags: -1} | Remove first element |
5. Adding Unique Items
| Aspect | Detail |
| $addToSet | Equality 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 ($)
| Form | Effect |
{"items.$": value} | First matched element from query filter |
| Requires | Array field in filter |
db.orders.updateOne(
{ _id: id, "items.sku": "A" },
{ $set: { "items.$.qty": 5 } }
);
7. Updating All Array Elements ($[])
| Form | Effect |
{"scores.$[]": newValue} | Update every element |
{"scores.$[]": {$mul: 1.1}} | Use with operators |
8. Using Filtered Positional Operator ($[identifier])
| Form | Effect |
$[elem] | Update elements matching arrayFilters entry |
| arrayFilters | Array of filter docs per identifier |
| Multiple | Multiple identifiers per update allowed |
db.classes.updateMany(
{},
{ $set: { "students.$[s].passed": true } },
{ arrayFilters: [ { "s.grade": { $gte: 70 } } ] }
);
9. Slicing Arrays
| Form | Effect |
$push: { items: { $each: [...], $slice: 100 } } | Keep first 100 |
$slice: -100 | Keep last 100 |
| Use case | Bounded log/activity feed |
10. Sorting Array Elements
| Form | Effect |
$push: { items: { $each: [...], $sort: {ts: -1} } } | Sort subdocs by field |
$sort: 1 | Sort scalar array ascending |
11. Limiting Array Size
| Pattern | Form |
| Bounded queue | $push: {recent: {$each: [x], $slice: -50}} |
| Top-N by score | $each + $sort + $slice |
12. Using $pullAll to Remove Multiple
| Form | Effect |
$pullAll: { tags: ["x","y"] } | Remove every element equal to any listed value |
| vs $pull | $pullAll uses equality; $pull uses match expression |