Working with arrays
Arrays are powerful but need care: bound their size and index the fields you search.
In this page:
Syntax
db.collection_name.updateOne(
filter,
{ $push: { array_field: { $each: [value], $slice: -n } } }
)
Working with arrays
Use $push with $slice to keep a fixed-size array, $addToSet for unique values, and positional operators like $ and $[] to update elements.
Multikey indexes cover array fields. Avoid arrays that grow without limit because documents are capped at 16 MB.
Note:
$push with $each and $slice keeps only the most recent N items.
Example: Working with arrays
test> db.feeds.insertOne({ _id: 1, recent: [] })
{ acknowledged: true, insertedId: 1 }
test> for (const n of [1, 2, 3, 4, 5]) db.feeds.updateOne({ _id: 1 }, { $push: { recent: { $each: ["post" + n], $slice: -3 } } })
test> db.feeds.findOne()
{ _id: 1, recent: [ 'post3', 'post4', 'post5' ] }
test> db.carts.insertOne({ _id: 1, items: [{ sku: "A", qty: 1 }, { sku: "B", qty: 2 }] })
{ acknowledged: true, insertedId: 1 }
test> db.carts.updateOne({ _id: 1 }, { $set: { "items.1.qty": 5 } }) // by position; the positional $ operator targets the matched element in real MongoDB
{ acknowledged: true, matchedCount: 1, modifiedCount: 1 }
test> db.carts.findOne()
{ _id: 1, items: [ { sku: 'A', qty: 1 }, { sku: 'B', qty: 5 } ] }
⚠️ Run this in your own terminal or Node.js environment.
Related Topics
Common Mistakes
- Unbounded arrays
- Updating arrays by rewriting the whole field
- Ignoring array position operators
Chapter Summary
- $slice keeps arrays bounded
- $addToSet keeps values unique
- Positional operators update elements
- Multikey indexes cover arrays
🔒
Chapter Quiz — Complete all 7 topics to unlock
0/7 topics done
Complete these topics first: