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.