- 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 $maxN returns. |
input |
An expression that resolves to the
array from which to return the maximal n elements. |
Behavior¶
- You cannot specify a value of
n
less than1
. $maxN
filters outnull
values found in theinput
array.- If the specified
n
is greater than or equal to the number of elements in theinput
array,$maxN
returns all elements in theinput
array. - If
input
resolves to a non-array value, the aggregation operation errors. - If
input
contains 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: