How to Use $push in Aggregation in MongoDB: Syntax and Examples
In MongoDB aggregation,
$push is used inside the $group stage to add values to an array for each group. It collects all values from documents in the group into an array, preserving order.Syntax
The $push operator is used within the $group stage of an aggregation pipeline. It adds values to an array for each group.
_id: Defines the group key.field: { $push: <expression> }: Creates an array of values from the grouped documents.
json
{
$group: {
_id: <grouping_key>,
<newArrayField>: { $push: <expression> }
}
}Example
This example groups documents by the category field and uses $push to collect all item names into an array for each category.
mongodb
db.products.aggregate([
{
$group: {
_id: "$category",
items: { $push: "$item" }
}
}
])Output
[
{ "_id" : "fruits", "items" : ["apple", "banana", "orange"] },
{ "_id" : "vegetables", "items" : ["carrot", "lettuce"] }
]
Common Pitfalls
Common mistakes when using $push include:
- Using
$pushoutside of a$groupstage, which causes errors. - Not specifying a grouping
_id, resulting in unexpected grouping behavior. - Using
$pushwhen you want unique values; in that case,$addToSetis better.
mongodb
/* Wrong: $push outside $group */ db.collection.aggregate([ { $push: "$field" } ]) /* Right: $push inside $group */ db.collection.aggregate([ { $group: { _id: "$category", values: { $push: "$field" } } } ])
Quick Reference
| Operator | Purpose | Usage Context |
|---|---|---|
| $push | Adds values to an array in grouped documents | Inside $group stage |
| $addToSet | Adds unique values to an array | Inside $group stage |
| $group | Groups documents by specified key | Aggregation pipeline stage |
Key Takeaways
Use $push inside the $group stage to collect values into arrays by group.
$push preserves the order of values as they appear in documents.
For unique values, prefer $addToSet instead of $push.
Always specify the _id field in $group to define grouping keys.
Using $push outside $group causes errors.