← Back to MongoDB Course | Chapter 9: Schema Design | Lesson 6 of 7

Working with arrays

Arrays are powerful but need care: bound their size and index the fields you search.

In this page:

  1. Working with arrays
Syntax
javascript
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

bash
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/chapter_summary/browser_support: on Hindi pages the view already swaps in the hi_ translation fields (or blanks these out if untranslated), so this renders correctly for both languages without a lang_code check here. #}
Common Mistakes
  1. Unbounded arrays
  2. Updating arrays by rewriting the whole field
  3. Ignoring array position operators
Chapter Summary
  • $slice keeps arrays bounded
  • $addToSet keeps values unique
  • Positional operators update elements
  • Multikey indexes cover arrays

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.