Bird
Raised Fist0
MongoDBquery~10 mins

$push accumulator for building arrays in MongoDB - Step-by-Step Execution

Choose your learning style10 modes available
Concept Flow - $push accumulator for building arrays
Start aggregation
↓
Group documents by key
↓
For each group
↓
$push adds each value to array
↓
Build array of values
↓
Output grouped document with array
The $push accumulator collects values from grouped documents into an array for each group.
Execution Sample
MongoDB
db.sales.aggregate([
  { $group: {
      _id: "$item",
      allPrices: { $push: "$price" }
  }}
])
Groups sales by item and collects all prices into an array for each item.
Execution Table
StepInput DocumentGroup Key (_id)Value to PushArray StateAction
1{"item": "apple", "price": 10}apple10[10]Start new group 'apple', push 10
2{"item": "banana", "price": 5}banana5[5]Start new group 'banana', push 5
3{"item": "apple", "price": 15}apple15[10, 15]Push 15 to 'apple' array
4{"item": "banana", "price": 7}banana7[5, 7]Push 7 to 'banana' array
5{"item": "apple", "price": 8}apple8[10, 15, 8]Push 8 to 'apple' array
6No more documents---Aggregation ends, output groups with arrays
💡 All documents processed, arrays built for each group.
Variable Tracker
VariableStartAfter 1After 2After 3After 4After 5Final
apple array[][10][10][10, 15][10, 15][10, 15, 8][10, 15, 8]
banana array[][][5][5][5, 7][5, 7][5, 7]
Key Moments - 3 Insights
Why does $push create an array even if there is only one document in the group?
$push always collects values into an array for consistency, so even one value is inside an array as shown in step 1 and 2 of the execution_table.
What happens if the group key (_id) changes between documents?
A new group is started for each unique _id, so separate arrays are built independently as seen for 'apple' and 'banana' groups in the execution_table.
Can $push add duplicate values to the array?
Yes, $push adds every value it sees without removing duplicates, so arrays may contain repeated values if input documents have them.
Visual Quiz - 3 Questions
Test your understanding
Look at the execution_table, what is the 'apple array' after step 3?
A[15]
B[10]
C[10, 15]
D[10, 15, 8]
💡 Hint
Check the 'Array State' column for step 3 in the execution_table.
At which step does the 'banana array' first get a value pushed?
AStep 1
BStep 2
CStep 3
DStep 4
💡 Hint
Look at the 'Group Key (_id)' and 'Array State' columns for 'banana' in the execution_table.
If a new document {"item": "apple", "price": 20} is added after step 5, what will be the final 'apple array'?
A[10, 15, 8, 20]
B[10, 15, 8]
C[20]
D[10, 15]
💡 Hint
Consider how $push adds each new value to the existing array as shown in the execution_table.
Concept Snapshot
$push accumulator in MongoDB aggregation
- Used inside $group stage
- Collects values from documents into an array
- Creates array even if one value
- Arrays can have duplicates
- Useful to gather all values per group
Full Transcript
The $push accumulator in MongoDB aggregation collects values from grouped documents into arrays. When grouping documents by a key, $push adds each value to an array for that group. For example, grouping sales by item and pushing prices builds arrays of prices per item. Each input document is processed: if the group key is new, a new array starts; if existing, the value is appended. This continues until all documents are processed, resulting in grouped documents with arrays of values. $push always creates arrays, even if only one value exists, and it includes duplicates if present. This behavior is shown step-by-step in the execution table and variable tracker, helping beginners understand how arrays build up during aggregation.

Practice

(1/5)
1. What does the $push accumulator do in a MongoDB aggregation pipeline?
easy
A. It removes duplicate values from an array.
B. It adds values to an array for each group in the aggregation.
C. It sorts the documents in the aggregation result.
D. It counts the number of documents in each group.

Solution

  1. Step 1: Understand the purpose of $push

    The $push accumulator collects values into an array for each group during aggregation.
  2. Step 2: Compare with other accumulators

    Unlike $addToSet which removes duplicates, $push simply appends values, allowing duplicates.
  3. Final Answer:

    It adds values to an array for each group in the aggregation. -> Option B
  4. Quick Check:

    $push = add values to array [OK]
Hint: Remember: $push always appends values to arrays [OK]
Common Mistakes:
  • Confusing $push with $addToSet which removes duplicates
  • Thinking $push sorts the array automatically
  • Assuming $push counts documents instead of collecting values
2. Which of the following is the correct syntax to use $push in a MongoDB aggregation $group stage?
easy
A. { $group: { _id: "$category", items: { $push: { "$item" } } } }
B. { $group: { _id: "$category", items: { $push: ["$item"] } } }
C. { $group: { _id: "$category", items: { $push: "$item" } } }
D. { $group: { _id: "$category", items: { push: "$item" } } }

Solution

  1. Step 1: Review correct $push syntax

    The $push operator requires a field name with a value to push, like $push: "$item".
  2. Step 2: Identify syntax errors in options

    { $group: { _id: "$category", items: { $push: ["$item"] } } } incorrectly uses an array around "$item". { $group: { _id: "$category", items: { $push: { "$item" } } } } uses braces instead of quotes. { $group: { _id: "$category", items: { push: "$item" } } } misses the $ sign before push.
  3. Final Answer:

    { $group: { _id: "$category", items: { $push: "$item" } } } -> Option C
  4. Quick Check:

    Correct $push syntax = { $group: { _id: "$category", items: { $push: "$item" } } } [OK]
Hint: Use $push: "fieldName" inside $group stage [OK]
Common Mistakes:
  • Forgetting the $ before push
  • Using arrays or objects incorrectly inside $push
  • Misplacing quotes around field names
3. Given the collection orders with documents:
{ "customer": "Alice", "product": "Pen" }
{ "customer": "Alice", "product": "Notebook" }
{ "customer": "Bob", "product": "Pen" }

What will be the result of this aggregation?
{ $group: { _id: "$customer", products: { $push: "$product" } } }
medium
A. [{ "_id": "Alice", "products": ["Pen", "Notebook"] }, { "_id": "Bob", "products": ["Pen"] }]
B. [{ "_id": "Alice", "products": "Pen" }, { "_id": "Bob", "products": "Pen" }]
C. [{ "_id": "Alice", "products": ["Notebook"] }, { "_id": "Bob", "products": ["Pen"] }]
D. [{ "_id": "Alice", "products": [] }, { "_id": "Bob", "products": [] }]

Solution

  1. Step 1: Group documents by customer

    The aggregation groups documents by the "customer" field, so Alice and Bob form separate groups.
  2. Step 2: Use $push to collect products

    For each group, $push collects all "product" values into an array. Alice has "Pen" and "Notebook", Bob has "Pen".
  3. Final Answer:

    [{ "_id": "Alice", "products": ["Pen", "Notebook"] }, { "_id": "Bob", "products": ["Pen"] }] -> Option A
  4. Quick Check:

    Group by customer + $push products = [{ "_id": "Alice", "products": ["Pen", "Notebook"] }, { "_id": "Bob", "products": ["Pen"] }] [OK]
Hint: Group by field, $push collects all matching values in array [OK]
Common Mistakes:
  • Expecting $push to return single value instead of array
  • Confusing $push with $first or $last accumulator
  • Ignoring grouping effect on output structure
4. You wrote this aggregation but it throws an error:
{ $group: { _id: "$category", items: { $push: "$item" } } }

What is the likely cause of the error?
medium
A. The field names "category" or "item" do not exist in the documents.
B. You forgot to include the $match stage before $group.
C. The $push operator cannot be used inside $group.
D. The _id field cannot be a string.

Solution

  1. Step 1: Check field existence in documents

    If the fields "category" or "item" do not exist in the documents, $push will fail because it tries to access missing fields.
  2. Step 2: Validate other options

    $push is valid inside $group, $match is optional, and _id can be a string. So these are not causes of error.
  3. Final Answer:

    The field names "category" or "item" do not exist in the documents. -> Option A
  4. Quick Check:

    Missing fields cause $push error [OK]
Hint: Verify fields exist before using $push on them [OK]
Common Mistakes:
  • Assuming $push requires $match stage
  • Thinking _id cannot be string
  • Believing $push is invalid inside $group
5. You want to group sales by store and collect all product names sold, but only unique products without duplicates. Which aggregation pipeline correctly uses $push and another operator to achieve this?
hard
A. { $group: { _id: "$store", products: { $push: "$product" } } }
B. { $group: { _id: "$store", products: { $push: { $each: "$product" } } } }
C. { $group: { _id: "$store", products: { $push: { $addToSet: "$product" } } } }
D. { $group: { _id: "$store", products: { $addToSet: "$product" } } }

Solution

  1. Step 1: Understand $push vs $addToSet

    $push collects all values including duplicates. $addToSet collects unique values only.
  2. Step 2: Identify correct usage for unique array

    To get unique products per store, use $addToSet: "$product" inside $group.
  3. Step 3: Analyze other options

    { $group: { _id: "$store", products: { $push: "$product" } } } uses $push (duplicates allowed). { $group: { _id: "$store", products: { $push: { $addToSet: "$product" } } } } nests $addToSet inside $push which is invalid. { $group: { _id: "$store", products: { $push: { $each: "$product" } } } } misuses $each inside $push.
  4. Final Answer:

    { $group: { _id: "$store", products: { $addToSet: "$product" } } } -> Option D
  5. Quick Check:

    Unique array needs $addToSet, not $push [OK]
Hint: Use $addToSet for unique arrays, $push allows duplicates [OK]
Common Mistakes:
  • Using $push when unique values are needed
  • Nesting $addToSet inside $push incorrectly
  • Misusing $each inside $push accumulator
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard