0
0
MongodbHow-ToBeginner · 3 min read

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 $push outside of a $group stage, which causes errors.
  • Not specifying a grouping _id, resulting in unexpected grouping behavior.
  • Using $push when you want unique values; in that case, $addToSet is 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

OperatorPurposeUsage Context
$pushAdds values to an array in grouped documentsInside $group stage
$addToSetAdds unique values to an arrayInside $group stage
$groupGroups documents by specified keyAggregation 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.