Definition
Returns the specified number of elements from the end of an array.
Note
Disambiguation
This page describes $lastN when used as an expression, which returns the specified number of elements from the end of an array.
You can also use $lastN in these other contexts:
$lastN (accumulator), used in grouping to return the lastnelements from each group.$lastN (window function), which is used in the$setWindowFieldsstage to return the lastnvalues from documents in a particular window.
Syntax
{ $lastN: { input: <expression>, n: <expression> } }
Options
Field | Type | Description |
|---|---|---|
| Expression | The array from which to return the last |
| Expression | The number of elements that |
Behavior
$lastNreturns elements in the same order they appear in the input array.$lastNdoes not filter outnullvalues in the input array.You cannot specify a value of
nless than1.If the specified
nis greater than or equal to the number of elements in theinputarray,$lastNreturns the entireinputarray.If
inputresolves to a non-array value, the expression errors.
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 the $lastN operator to return the last three cast members for each movie. The cast members are returned in the new field lastThreeCast created by $addFields.
db.movies.aggregate( [ { $match: { title: { $in: [ "The Godfather", "Spirited Away", "The Dark Knight" ] } } }, { $addFields: { lastThreeCast: { $lastN: { input: "$cast", n: 3 } } } }, { $project: { _id: 0, title: 1, cast: 1, lastThreeCast: 1 } }, { $sort: { title: 1 } } ] )
The preceding pipeline:
Uses
$matchto filter for three specific movies.Uses
$addFieldswith$lastNto create a new fieldlastThreeCastcontaining the last three elements from thecastarray.Uses
$projectto include only thetitle,cast, andlastThreeCastfields in the output.Uses
$sortto sort the results by title.