Definition
$maxNReturns an aggregation of the maximum value
nelements within a group. If the group contains fewer thannelements,$maxNreturns all elements in the group.
The $maxN accumulator is available in these stages:
Note
Other Uses of $maxN
This page describes $maxN when used as an accumulator. Accumulators return an aggregated value like sum, maximum, or minimum across a group of input documents.
You can also use $maxN in these other contexts:
$maxN (expression), which returns the largestnvalues from an array.$maxN (window function), which is used in the$setWindowFieldsstage to return the largestnvalues from documents in a particular window.
Syntax
{ $maxN: { input: <expression>, n: <expression> } }
Field | Type | Description |
|---|---|---|
| Expression | The expression evaluated for each element in the group. |
| Expression | The number of elements that |
Behavior
Result Type
When $maxN compares values of different types, the ordering of types follows the BSON comparison order.
Null and Missing Values
$maxN filters out null and missing values.
The following aggregation demonstrates how $maxN handles null and missing values:
db.aggregate( [ { $documents: [ { title: "Fight Club", genre: "Drama", rating: 8.9 }, { title: "The Matrix", genre: "Drama", rating: 8.7 }, { title: "The Green Mile", genre: "Drama", rating: 8.5 }, { title: "Magnolia", genre: "Drama" }, { title: "Dogma", genre: "Drama", rating: null } ] }, { $group: { _id: "$genre", topFourRatings: { $maxN: { input: "$rating", n: 4 } } } } ] )
[ { _id: 'Drama', topFourRatings: [ 8.9, 8.7, 8.5 ] } ]
In this example:
$documentscreates the literal documents that contain movie ratings.$groupgroups the documents bygenre. This example has only onegenre,Drama.Magnoliahas a missingratingandDogmahas a nullrating. Both values are filtered out.Since only 3 documents have valid ratings,
$maxNreturns 3 values even thoughn = 4.
Comparison of $maxN and $topN Accumulators
You can use $maxN or $topN to return the highest-ranked n elements from a group. The choice between them depends on whether your input documents are already sorted.
If the input documents are already sorted, use
$maxNto return the maximumnvalues.If you need to sort and select the top
nelements at the same time, use$topNto accomplish both with a single accumulator.
Examples
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 for a Single Year
You can use the $maxN accumulator to find the three highest IMDb ratings for movies released in a single year.
db.movies.aggregate( [ { $match: { year: 1999, "imdb.rating": { $exists: true } } }, { $group: { _id: 1999, topThreeRatings: { $maxN: { input: "$imdb.rating", n: 3 } } } } ] )
The preceding pipeline:
Uses
$matchto filter for movies released in1999that have animdb.ratingfield.Groups all matching documents into a single group with
_id: 1999.Specifies
"$imdb.rating"as theinputfor$maxN.Uses
$maxNto return the three highest ratings withn: 3.
Find the Three Highest Rated Movies Across Multiple Years
You can use the $maxN accumulator to find the three highest rated movies for each year in a set of years.
db.movies.aggregate( [ { $match: { year: { $in: [ 1999, 2000, 2001 ] }, "imdb.rating": { $exists: true } } }, { $group: { _id: "$year", topThreeRatings: { $maxN: { input: "$imdb.rating", n: 3 } } } }, { $sort: { _id: 1 } } ] )
The preceding pipeline:
Set n Based on the Group Key
You can assign the value of n dynamically based on the group key. In this example, the $cond expression uses the year field to change the value of n:
db.movies.aggregate( [ { $match: { year: { $in: [ 1999, 2000, 2001 ] }, "imdb.rating": { $exists: true } } }, { $group: { _id: { year: "$year" }, topRatedMovies: { $maxN: { input: "$imdb.rating", n: { $cond: { if: { $eq: [ "$year", 2001 ] }, then: 3, else: 1 } } } } } }, { $sort: { "_id.year": 1 } } ] )
The preceding pipeline:
Filters for movies released in
1999,2000, or2001that have animdb.ratingfield.Groups movies by
year.Uses the
$condexpression to return3ratings for the year2001and1rating for all other years.
In the output, 2001 returns three ratings while 1999 and 2000 each return one rating.