Definition
Returns an array of all values, including duplicates, that result from applying an expression to each document in a window.
Note
Disambiguation
This page describes $push when used as a window function.
You can also use $push in these other contexts:
$push (accumulator), which returns the resulting array after applying an expression to each document in a group.$push (update operator), which appends a value to an array field in a document.
Syntax
{ $setWindowFields: { ... output: { <field>: { $push: <expression> } } } }
Behavior
$push includes all values in the window, including duplicates. The order of elements in the output array corresponds to the sort order specified in the $setWindowFields sortBy field.
Example
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.
This example uses the $push window function to build a running list of genres across movies from 2002. For each movie, $push adds the movie's primary genre to genresSeenSoFar, retaining all values including duplicates.
db.movies.aggregate( [ { $match: { year: 2002, genres: { $exists: true, $ne: [] } } }, { $addFields: { primaryGenre: { $first: "$genres" } } }, { $setWindowFields: { sortBy: { title: 1 }, output: { genresSeenSoFar: { $push: "$primaryGenre", window: { documents: [ "unbounded", "current" ] } } } } }, { $project: { _id: 0, genresSeenSoFar: "$genresSeenSoFar", year: "$year", title: "$title", genre: "$primaryGenre", totalGenreCount: { $size: "$genresSeenSoFar" } } }, { $limit: 8 } ] )
In the example:
The
$matchstage filters to movies from 2002 with genre information.The
$addFieldsstage adds aprimaryGenrefield that contains the first element in thegenresarray.The
$setWindowFieldsstage uses$pushwith anunboundedtocurrentwindow to accumulate all genres from the beginning of the result set up to the current document.The
$projectstage reshapes the output and calculatestotalGenreCountto show how the array grows with each document.The
$limitstage restricts output to 8 documents to improve readability.
totalGenreCount increases by one with every document. The seventh document ('3 Extremes II') has genre Horror, which was already in the array, so Horror appears twice in genresSeenSoFar. This demonstrates that $push includes duplicate values, unlike $addToSet, which adds only unique values.