Definition
Returns the result of evaluating a specified expression over the last n elements in a group. The results are meaningful only if the input data to the grouping stage has a defined sort order. If the group contains fewer than n elements, $lastN returns all elements in the group.
The $lastN accumulator is available in these stages:
Note
Disambiguation
This page describes $lastN when used as an accumulator. Accumulators return an aggregated value like sum, maximum, or minimum across a group of input documents.
You can also use $lastN in these other contexts:
$lastN (expression), which returns the specified number of elements from the end of an array.$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 |
| Expression | The number of elements that |
Behavior
Null and Missing Values
$lastNdoes not filter out null values.$lastNconverts missing values to null.
Comparison of $lastN and $bottomN
You can use $lastN and $bottomN to return the last n elements from a group. However, the difference of when to use each depends on whether your input documents are already sorted.
If the documents coming into
$groupare already ordered, you should use$lastN.If you're sorting and selecting the bottom
nelements then you can use$bottomNto accomplish both tasks with one accumulator.
Examples
The examples on this page use the movies collection in the sample_mflix sample dataset. To learn how to load the sample dataset into your MongoDB deployment, see Import Sample Data Into Your Atlas Deployment.
Find the Last Three Movies for a Single Genre
You can use the $lastN accumulator to find the most-recently released movies in a particular genre.
db.movies.aggregate( [ { $match: { genres: "Horror", year: { $type: "int" } } }, { $sort: { year: 1, title: 1 } }, { $group: { _id: "Horror", lastThreeMovies: { $lastN: { input: [ "$title", "$year" ], n: 3 } } } } ] )
The preceding pipeline:
Uses
$matchto filter the results to movies whereHorroris included in thegenresarray, and whereyearis an integer.Sorts the results by
yearin ascending order, then bytitlealphabetically as a tiebreaker.Groups all resulting documents into a single group.
Specifies the fields that are input for
$lastNwithinput : ["$title", "$year"].Uses
$lastNto return the last three documents (sorted by year ascending, withtitleas a tiebreaker) for theHorrorgenre withn: 3.
Find the Last Three Movies Across Multiple Genres
You can use the $lastN accumulator to find the last n input fields in each genre.
db.movies.aggregate( [ { $match: { year: { $type: "int" } } }, { $unwind: "$genres" }, { $sort: { year: 1, title: 1 } }, { $group: { _id: "$genres", movies: { $lastN: { input: [ "$title", "$year" ], n: 3 } } } }, { $sort: { _id: 1 } }, { $limit: 5 } ] )
The preceding pipeline:
Uses
$matchto filter to movies whereyearis an integer.Uses
$unwindto create a separate document for each genre in thegenresarray.Sorts the results by
yearin ascending order, then bytitlealphabetically.Uses
$groupto group the results bygenres.Uses
$lastNto return the last three documents (by year ascending, withtitleas a tiebreaker) for each genre withn: 3.Specifies the fields that are input for
$lastNwithinput : ["$title", "$year"].Limits the output to five documents to improve readability.
Set n Based on the Group Key
You can assign the value of n dynamically based on the group key. In this example, the $cond expression uses the rated field to change the value of n:
db.movies.aggregate( [ { $match: { rated: { $in: [ "G", "PG", "PG-13", "R" ] }, year: { $type: "int" }, title: { $regex: "^[A-Za-z0-9]" } } }, { $sort: { title: 1 } }, { $group: { _id: { rated: "$rated" }, movies: { $lastN: { input: "$title", n: { $cond: { if: { $eq: ["$rated", "PG"] }, then: 3, else: 1 } } } } } }, { $sort: { "_id.rated": 1 } } ] )
The preceding pipeline:
Filters for movies with content ratings of
G,PG,PG-13, orR, whereyearis an integer andtitlestarts with an alphanumeric character.Sorts the results alphabetically by
title.Groups movies by
rated(the content rating).Uses the
$condexpression to return3movies forPG-rated movies and1movie for all other ratings.
In the output, the PG rating returns 3 movies, while G, PG-13, and R ratings each return 1 movie.