For AI agents: a documentation index is available at https://www.mongodb.com/docs/llms.txt — markdown versions of all pages are available by appending .md to any URL path.
See how MongoDB 9.0 delivers up to 2x higher throughput.
MongoDB Branding Shape
Register now >
Docs Menu

$push (accumulator operator)

$push

Returns an array of all values that result from applying an expression to each document in a group.

The $push accumulator is available in these stages:

Note

Disambiguation

This page describes $push when used as an accumulator. Accumulators return an aggregated value across a group of input documents.

You can also use $push in these other contexts:

{ $push: <expression> }

For more information on expressions, see Expressions.

When you use $push as an accumulator, the order of the documents coming into the pipeline determines the order of the documents in the output array. To guarantee a defined order, place a $sort stage before the $group stage.

The examples on this page use data from the sample_mflix dataset. For details on how to load this dataset into your self-managed MongoDB deployment, see Load the Sample Dataset. If you made any modifications to the sample databases, you may need to drop and recreate the databases to run the examples on this page.

The following operation groups movies by director and uses the $push accumulator to collect the primary genre of each film directed by that director.

db.movies.aggregate( [
{
$match: {
year: { $gte: 2010, $lte: 2015 },
genres: { $exists: true, $ne: [] },
directors: { $exists: true, $ne: [] }
}
},
{
$unwind: "$directors"
},
{
$group: {
_id: "$directors",
genres: { $push: { $first: "$genres" } }
}
},
{
$sort: { _id: 1 }
},
{
$limit: 5
}
] )

The preceding pipeline:

  • Uses $match to filter to movies from 2010-2015 that have genre and director information.

  • Uses $unwind to create a separate document for each director in the directors array.

  • Groups the resulting documents by director and uses $push to collect the primary genre of each film.

  • Sorts the results by director name in alphabetical order.

  • Limits the output to five directors.

In the output, A.R. Murugadoss has Action listed twice because they directed two films with Action as the primary genre. This demonstrates that $push includes duplicate values, unlike $addToSet, which returns an array of unique values.