- Reference >
- Operators >
- Aggregation Pipeline Operators >
- $lastN (array operator)
$lastN (array operator)¶
On this page
Definition¶
-
$lastN
¶ New in version 5.2.
Returns a specified number of elements from the end of an array.
See also
Syntax¶
$lastN
has the following syntax:
Field | Description |
---|---|
n |
An expression that resolves to a
positive integer. The integer specifies the number of array elements
that $lastN returns. |
input |
An expression that resolves to the
array from which to return n elements. |
Behavior¶
$lastN
returns elements in the same order they appear in the input array.$lastN
does not filter outnull
values in the input array.- You cannot specify a value of
n
less than1
. - If the specified
n
is greater than or equal to the number of elements in theinput
array,$lastN
returns theinput
array. - If
input
resolves to a non-array value, the aggregation operation errors.
Example¶
The collection games
has the following documents:
The following example uses the $lastN
operator to retrieve the
last three scores for each player. The scores are returned in the new field
lastScores
created by $addFields
.
The operation returns the following results:
Search Results
- MongoDB Manual
- All Results