Definition
Note
Other Uses of $maxN
This page describes $maxN when used as an expression, which returns the largest n values from an array.
You can also use $maxN in these other contexts:
$maxN (accumulator), which returns the maximumnvalues within a group.$maxN (window function), which is used in the$setWindowFieldsstage to return the largestnvalues from documents in a particular window.
Syntax
{ $maxN: { n: <expression>, input: <expression> } }
Field | Type | Description |
|---|---|---|
| Expression | Specifies the number of elements to return. Must resolve to a positive integer. |
| Expression | Specifies the input array from which to return the maximum |
Behavior
$maxNfilters outnullvalues.If the
inputarray contains fewer thannelements,$maxNreturns all elements in the array.If
inputresolves to a non-array value, the operation returns an error.If
inputcontains both numeric and string elements, string elements are sorted before numeric elements according to the BSON comparison order.
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.
The following example uses $maxN to return the two alphabetically last cast members for each movie, stored in a new topTwoCast field created by $addFields.
db.movies.aggregate( [ { $match: { title: { $in: [ "The Godfather", "Spirited Away", "The Dark Knight" ] } } }, { $addFields: { topTwoCast: { $maxN: { n: 2, input: "$cast" } } } }, { $project: { _id: 0, title: 1, cast: 1, topTwoCast: 1 } }, { $sort: { title: 1 } } ] )
The preceding pipeline:
Uses
$matchto filter for three specific movies.Uses
$addFieldswith$maxNto create a new fieldtopTwoCastcontaining the two alphabetically last values from thecastarray withn: 2.Uses
$projectto include only thetitle,cast, andtopTwoCastfields in the output.Uses
$sortto sort the results by title.