- Reference >
- Operators >
- Aggregation Pipeline Operators >
- $maxN (array operator)
$maxN (array operator)¶
On this page
Syntax¶
$maxN has the following syntax:
| Field | Description | 
|---|---|
| n | An expression that resolves to a
positive integer. The integer specifies the number of array elements
that $maxNreturns. | 
| input | An expression that resolves to the
array from which to return the maximal nelements. | 
Behavior¶
- You cannot specify a value of nless than1.
- $maxNfilters out- nullvalues found in the- inputarray.
- If the specified nis greater than or equal to the number of elements in theinputarray,$maxNreturns all elements in theinputarray.
- If inputresolves to a non-array value, the aggregation operation errors.
- If inputcontains both numeric and string elements, the string elements are sorted before numeric elements according to the BSON comparison order.
Example¶
Create a scores collection with the following documents:
The following example uses the $maxN operator to retrieve the two
highest scores for each player. The highest scores are returned in the new field
maxScores created by $addFields.
The operation returns the following results: