Definition
Returns an array containing the last n elements within a window.
Note
Disambiguation
This page describes $lastN when used as a window function.
You can also use $lastN in these other contexts:
$lastN (accumulator), used in grouping to return the lastnelements from each group.$lastN (expression), which returns the specified number of elements from the end of an array.
Syntax
{ $setWindowFields: { ... output: { <field>: { $lastN: { input: <expression>, n: <expression> } } } } }
Options
Field | Type | Description |
|---|---|---|
| Expression | The |
| Expression | The number of elements that If the window contains fewer than |
Behavior
$lastN has the following behaviors for null and missing values:
$lastNdoes not filter out null values.$lastNconverts missing values to null.
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.
This example uses $setWindowFields to partition movies by year, sort them by imdb.rating in descending order, and return the three lowest-rated movies from each year.
db.movies.aggregate( [ { $match: { year: { $in: [ 1979, 1985, 1992 ] }, "imdb.rating": { $lte: 4.5, $gt: 0 } } }, { $setWindowFields: { partitionBy: "$year", sortBy: { "imdb.rating": -1, "title": 1 }, output: { lowestRatedThreeMoviesInYear: { $lastN: { input: "$title", n: 3 }, window: { documents: [ "unbounded", "unbounded" ] } } } } }, { $project: { _id: 0, title: 1, year: 1, "imdb.rating": 1, lowestRatedThreeMoviesInYear: 1 } }, { $sort: { year: 1, "imdb.rating": -1, "title": 1 } } ] )
The preceding pipeline:
Uses the
$matchstage to filter the results to movies released in 1979, 1985, and 1992 with an IMDb rating of 4.5 or lower.Uses
$setWindowFieldsto partition movies byyearand sort them byimdb.ratingin descending order withtitleas a tiebreaker. The stage uses$lastNwithn: 3to createlowestRatedThreeMoviesInYearfrom a window defined asdocuments: [ "unbounded", "unbounded" ].Uses
$projectto include only thetitle,year,imdb.rating, andlowestRatedThreeMoviesInYearfields in the output.Uses
$sortto sort the results by year, rating, and title.