Array Update Operators
Arrays have their own update operators, so you can change one element without rewriting the whole array.
| Operator | Effect |
|---|---|
$push |
append a value (with $each, several values) |
$addToSet |
append a value only if it isn't already present |
$pull |
remove every element matching a value or condition |
$pullAll |
remove every occurrence of the listed values |
$pop |
remove the last (1) or first (-1) element |
$ |
update the first element that matched the filter |
$[] |
update all elements |
$[name] |
update the elements matching an arrayFilters condition |
$push and $each
db.products.updateOne({ _id: 2 }, { $push: { tags: 'bestseller' } });
db.products.updateOne({ _id: 2 }, { $push: { tags: { $each: ['organic', 'fair-trade'] } } });
print(db.products.findOne({ _id: 2 }, { tags: 1 }));{
_id: 2,
tags: [ 'medium', 'ground', 'bestseller', 'organic', 'fair-trade' ]
}
Without $each, pushing an array would add the array itself as one nested element.
$push has modifiers that keep an array tidy: $sort orders it after the push and $slice trims it. Together they keep a "last 3 events" list:
db.activity.insertOne({ _id: 'ada', recent: [] });
for (const page of ['home', 'beans', 'grinders', 'cart', 'checkout']) {
db.activity.updateOne({ _id: 'ada' }, { $push: { recent: { $each: [page], $slice: -3 } } });
}
print(db.activity.findOne());{ _id: 'ada', recent: [ 'grinders', 'cart', 'checkout' ] }
$addToSet: no duplicates
db.customers.updateOne({ _id: 2 }, { $addToSet: { interests: 'coffee' } });
db.customers.updateOne({ _id: 2 }, { $addToSet: { interests: 'coffee' } });
db.customers.updateOne({ _id: 2 }, { $addToSet: { interests: { $each: ['tea', 'snacks'] } } });
print(db.customers.findOne({ _id: 2 }, { interests: 1 }));{ _id: 2, interests: [ 'tea', 'coffee', 'snacks' ] }
'coffee' was added once, and 'tea' was skipped because Alan already had it.
Removing elements: $pull, $pullAll and $pop
db.products.updateOne({ _id: 3 }, { $pull: { tags: 'whole-bean' } });
print(db.products.findOne({ _id: 3 }).tags);
db.products.updateOne({ _id: 9 }, { $pop: { tags: 1 } });
print(db.products.findOne({ _id: 9 }).tags);
// remove cheap line items from an order: $pull with a condition
db.orders.updateOne({ _id: 1005 }, { $pull: { items: { price: { $lt: 10 } } } });
print(db.orders.findOne({ _id: 1005 }).items.map(i => i.name));[ 'light', 'single-origin' ]
[ 'black', 'loose-leaf' ]
[ 'Pour-Over Dripper', 'House Blend' ]
Note: Removing items from an order doesn't change its stored
total. Keeping derived values in sync is your application's job, or the job of an update pipeline.
The positional operator $
$ stands for "the first array element that matched the filter". The filter must therefore contain a condition on the array:
// customer changed the quantity of the House Blend in order 1014
db.orders.updateOne(
{ _id: 1014, 'items.productId': 2 },
{ $set: { 'items.$.qty': 3 } }
);
print(db.orders.findOne({ _id: 1014 }).items);[
{ productId: 7, name: 'Earl Grey', qty: 1, price: 9.5 },
{ productId: 2, name: 'House Blend', qty: 3, price: 18 }
]
All elements: $[]
db.orders.updateOne({ _id: 1012 }, { $set: { 'items.$[].shipped': true } });
print(db.orders.findOne({ _id: 1012 }).items);[
{
productId: 4,
name: 'Colombia Supremo',
qty: 2,
price: 21,
shipped: true
},
{
productId: 15,
name: 'Paper Filters (100)',
qty: 1,
price: 6,
shipped: true
}
]
Filtered elements: $[name] with arrayFilters
arrayFilters names a condition, and $[name] applies the update to every element that satisfies it. Here every line item cheaper than $10, in every order, gets a 50% discount:
const res = db.orders.updateMany(
{ 'items.price': { $lt: 10 } },
{ $mul: { 'items.$[cheap].price': 0.5 } },
{ arrayFilters: [{ 'cheap.price': { $lt: 10 } }] }
);
print(res.matchedCount, 'orders changed');
print(db.orders.findOne({ _id: 1003 }).items);11 orders changed
[
{ productId: 7, name: 'Earl Grey', qty: 3, price: 4.75 },
{ productId: 16, name: 'Almond Biscotti', qty: 2, price: 3.75 }
]
Test yourself
tags is ['a', 'b']. What is it after { $push: { tags: ['c', 'd'] } }?
['a', 'b', 'c', 'd']['a', 'b', ['c', 'd']]['c', 'd']- An error
Which operator appends a value only if it is not in the array yet?
- $push
- $addToSet
- $each
- $set
In updateOne({ 'items.productId': 7 }, { $set: { 'items.$.qty': 2 } }), what does $ refer to?
- Every element
- The last element
- The first element that matched
items.productId: 7 - A variable named $