0
0
MongoDBquery~5 mins

$push accumulator for building arrays in MongoDB

Choose your learning style9 modes available
Introduction

The $push accumulator helps you collect values into an array while grouping data. It is useful when you want to gather related items together.

You want to list all products bought by each customer.
You need to collect all comments for each blog post.
You want to group all tags used in articles by category.
You want to gather all scores of a player in a game session.
Syntax
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.

Examples
Groups orders by customer and collects all product names into an array.
MongoDB
db.orders.aggregate([
  {
    $group: {
      _id: "$customerId",
      products: { $push: "$productName" }
    }
  }
])
Groups comments by post and gathers all comment texts into an array.
MongoDB
db.comments.aggregate([
  {
    $group: {
      _id: "$postId",
      allComments: { $push: "$commentText" }
    }
  }
])
Groups scores by player and collects all their scores into an array.
MongoDB
db.scores.aggregate([
  {
    $group: {
      _id: "$playerId",
      scores: { $push: "$score" }
    }
  }
])
Sample Program

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.

MongoDB
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)
OutputSuccess
Important Notes

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.

Summary

$push collects values into an array during grouping.

It keeps all values, including duplicates.

Use it inside $group stage in aggregation.