Definition
Returns an array containing the maximum n elements within a window.
Note
Other Uses of $maxN
This page describes $maxN when used as a window function.
You can also use $maxN in these other contexts:
$maxN (accumulator), which returns the maximumnvalues within a group.$maxN (expression), which returns the largestnvalues from an array.
Syntax
{ $setWindowFields: { ... output: { <field>: { $maxN: { input: <expression>, n: <expression> }, window: { documents: [ <lower boundary>, <upper boundary> ] } } } } }
Options
Field | Type | Description |
|---|---|---|
| Expression | The expression evaluated over each document in the window. |
| Expression | The number of elements that If the window contains fewer than |
Behavior
Null and Missing Values
$maxN filters out null and missing values.
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 $maxN in $setWindowFields to return the three highest-rated movies for each year. The window spans the entire partition, so every document in the same year receives the same topThreeRatedInYear value.
db.movies.aggregate( [ { $match: { year: { $in: [ 1999, 2001 ] }, "imdb.rating": { $gte: 8.5 } } }, { $setWindowFields: { partitionBy: "$year", sortBy: { "imdb.rating": -1 }, output: { topThreeRatedInYear: { $maxN: { input: [ "$imdb.rating", "$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 } } ] )
The preceding pipeline:
Uses
$matchto filter for movies released in1999or2001with an IMDb rating of8.5or higher.Uses
$setWindowFieldsto partition movies byyearand sort them byimdb.ratingin descending order. The stage uses$maxNwithn: 3to createtopThreeRatedInYearfrom a window spanning the entire partition (documents: ["unbounded", "unbounded"]).Uses
$projectto include only thetitle,year,imdb.rating, andtopThreeRatedInYearfields in the output.Uses
$sortto sort the results by year ascending and rating descending.