Definition
Returns the last element of an array.
Note
Disambiguation
This page describes $last when used as an expression, which returns the last element of an array.
You can also use $last in these other contexts:
$last (accumulator), used in grouping to return a value for the last document in each group.$last (window function), used in the$setWindowFieldsstage to return a value for the last document in a window.
Syntax
{ $last: <expression> }
The <expression> must evaluate to an array.
Behavior
If the array is empty,
$lastreturnsnull.If the expression evaluates to
nullor refers to a missing field,$lastreturnsnull.
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 $last to return the last cast member listed for each movie:
db.movies.aggregate( [ { $match: { title: { $in: [ "The Godfather", "Spirited Away", "The Dark Knight" ] } } }, { $addFields: { lastCast: { $last: "$cast" } } }, { $project: { _id: 0, title: 1, cast: 1, lastCast: 1 } }, { $sort: { title: 1 } } ] )
In the preceding pipeline:
$matchfilters for three specific movies.$addFieldswith$lastcreates a new fieldlastCastcontaining the last element of thecastarray.$projectincludes only thetitle,cast, andlastCastfields in the output.$sortsorts the results by title.