The $push accumulator helps you collect values into an array while grouping data. It is useful when you want to gather related items together.
$push accumulator for building arrays in MongoDB
db.collection.aggregate([
{
$group: {
_id: <grouping_key>,
arrayField: { $push: <expression> }
}
}
])$push adds each value to an array in the grouped result.
If you want unique values, consider $addToSet instead.
db.orders.aggregate([
{
$group: {
_id: "$customerId",
products: { $push: "$productName" }
}
}
])db.comments.aggregate([
{
$group: {
_id: "$postId",
allComments: { $push: "$commentText" }
}
}
])db.scores.aggregate([
{
$group: {
_id: "$playerId",
scores: { $push: "$score" }
}
}
])This example inserts sales records with customer IDs and products. Then it groups by customerId and collects all products bought into an array called productsBought.
db.sales.insertMany([
{ customerId: 1, product: "Apple" },
{ customerId: 1, product: "Banana" },
{ customerId: 2, product: "Carrot" },
{ customerId: 1, product: "Date" },
{ customerId: 2, product: "Eggplant" }
])
const result = db.sales.aggregate([
{
$group: {
_id: "$customerId",
productsBought: { $push: "$product" }
}
}
]).toArray()
printjson(result)Time complexity: Depends on the number of documents; grouping and pushing values is generally O(n).
Space complexity: The array size grows with the number of grouped items.
Common mistake: Using $push without grouping will not work; it must be inside a $group stage.
Use $push when you want to keep all values including duplicates. Use $addToSet if you want only unique values.
$push collects values into an array during grouping.
It keeps all values, including duplicates.
Use it inside $group stage in aggregation.
Practice
$push accumulator do in a MongoDB aggregation pipeline?Solution
Step 1: Understand the purpose of $push
The$pushaccumulator collects values into an array for each group during aggregation.Step 2: Compare with other accumulators
Unlike$addToSetwhich removes duplicates,$pushsimply appends values, allowing duplicates.Final Answer:
It adds values to an array for each group in the aggregation. -> Option BQuick Check:
$push= add values to array [OK]
- Confusing $push with $addToSet which removes duplicates
- Thinking $push sorts the array automatically
- Assuming $push counts documents instead of collecting values
$push in a MongoDB aggregation $group stage?Solution
Step 1: Review correct $push syntax
The$pushoperator requires a field name with a value to push, like$push: "$item".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.Final Answer:
{ $group: { _id: "$category", items: { $push: "$item" } } } -> Option CQuick Check:
Correct $push syntax = { $group: { _id: "$category", items: { $push: "$item" } } } [OK]
- Forgetting the $ before push
- Using arrays or objects incorrectly inside $push
- Misplacing quotes around field names
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" } } }Solution
Step 1: Group documents by customer
The aggregation groups documents by the "customer" field, so Alice and Bob form separate groups.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".Final Answer:
[{ "_id": "Alice", "products": ["Pen", "Notebook"] }, { "_id": "Bob", "products": ["Pen"] }] -> Option AQuick Check:
Group by customer + $push products = [{ "_id": "Alice", "products": ["Pen", "Notebook"] }, { "_id": "Bob", "products": ["Pen"] }] [OK]
- Expecting $push to return single value instead of array
- Confusing $push with $first or $last accumulator
- Ignoring grouping effect on output structure
{ $group: { _id: "$category", items: { $push: "$item" } } }What is the likely cause of the error?
Solution
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.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.Final Answer:
The field names "category" or "item" do not exist in the documents. -> Option AQuick Check:
Missing fields cause $push error [OK]
- Assuming $push requires $match stage
- Thinking _id cannot be string
- Believing $push is invalid inside $group
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?Solution
Step 1: Understand $push vs $addToSet
$push collects all values including duplicates. $addToSet collects unique values only.Step 2: Identify correct usage for unique array
To get unique products per store, use $addToSet: "$product" inside $group.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.Final Answer:
{ $group: { _id: "$store", products: { $addToSet: "$product" } } } -> Option DQuick Check:
Unique array needs $addToSet, not $push [OK]
- Using $push when unique values are needed
- Nesting $addToSet inside $push incorrectly
- Misusing $each inside $push accumulator
Ready to prove it?
Pass the test and this pattern moves unknown
