Definition
Returns the top n elements within a particular window, according to the specified sort order.
Note
Other Uses of $topN
This page describes $topN when used as a window function.
You can also use $topN in these other contexts:
$topN (accumulator), which returns the topnelements within a group according to the specified sort order.$topN (expression), which returns the topnelements from an array.
Syntax
{ $setWindowFields: { ... output: { <field>: { $topN: { n: <expression>, output: <expression>, sortBy: { <field1>: <sort order>, <field2>: <sort order>, ... } } } } } }
Options
Field | Necessity | Description |
|---|---|---|
| Required | Number of results to return. Must resolve to a positive integral value. If the window contains fewer than |
| Required | Determines the output for each document in the window. Can be any expression. |
| Required | Defines the ranking order of elements within the window, with syntax similar to |
Behavior
Null and Missing Values
$topNdoes not filter out null values.$topNconverts missing values to null.
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.
Find the Three Highest Rated Movies in a Window
This example uses $topN in $setWindowFields to return each movie with the three highest-rated movies released in the same year.
db.movies.aggregate( [ { $match: { year: { $in: [ 1999, 2001 ] }, "imdb.rating": { $gte: 8.5 } } }, { $setWindowFields: { partitionBy: "$year", output: { topThreeRatedInYear: { $topN: { sortBy: { "imdb.rating": -1, title: 1 }, output: { rating: "$imdb.rating", title: "$title" }, n: 3 }, window: { documents: [ "unbounded", "unbounded" ] } } } } }, { $project: { _id: 0, title: 1, year: 1, "imdb.rating": 1, topThreeRatedInYear: 1 } }, { $sort: { year: 1, "imdb.rating": -1 } } ] )
In the preceding example:
$matchfilters for movies released in1999or2001with an IMDb rating of at least8.5.$setWindowFieldspartitions the documents byyear.window: { documents: [ "unbounded", "unbounded" ] }spans the entire year partition, so$topNconsiders all documents in the year when determining the three highest-rated movies.$topNusessortBy: { "imdb.rating": -1, title: 1 }to rank movies by IMDb score and usestitleas a tie-breaker. Every document in the same year receives the sametopThreeRatedInYearvalue.$projectremoves unneeded fields to highlight the window function result.$sortsorts the output by year ascending and rating descending.