Docs Menu

$lastN (array operator)

On this page

  • Definition
  • Syntax
  • Behavior
  • Example
$lastN

New in version 5.2.

Returns a specified number of elements from the end of an array.

Tip
See also:

$lastN has the following syntax:

{ $lastN: { n: <expression>, input: <expression> } }
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.
  • $lastN returns elements in the same order they appear in the input array.
  • $lastN does not filter out null values in the input array.
  • You cannot specify a value of n less than 1.
  • If the specified n is greater than or equal to the number of elements in the input array, $lastN returns the input array.
  • If input resolves to a non-array value, the aggregation operation errors.

The collection games has the following documents:

db.games.insertMany([
{ "playerId" : 1, "score" : [ 1, 2, 3 ] },
{ "playerId" : 2, "score" : [ 12, 90, 7, 89, 8 ] },
{ "playerId" : 3, "score" : [ null ] },
{ "playerId" : 4, "score" : [ ] },
{ "playerId" : 5, "score" : [ 1293, null, 3489, 9 ]},
{ "playerId" : 6, "score" : [ "12.1", 2, NumberLong("2090845886852"), 23 ]}
])

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.

db.games.aggregate([
{ $addFields: { lastScores: { $lastN: { n: 3, input: "$score" } } } }
])

The operation returns the following results:

[{
"playerId": 1,
"score": [ 1, 2, 3 ],
"lastScores": [ 1, 2, 3 ]
},
{
"playerId": 2,
"score": [ 12, 90, 7, 89, 8 ],
"lastScores": [ 7, 89, 8 ]
},
{
"playerId": 3,
"score": [ null ],
"lastScores": [ null ]
},
{
"playerId": 4,
"score": [ ],
"lastScores": [ ]
},
{
"playerId": 5,
"score": [ 1293, null, 3489, 9 ],
"lastScores": [ null, 3489, 9 ]
},
{
"playerId": 6,
"score": [ "12.1", 2, NumberLong("2090845886852"), 23 ],
"lastScores": [ 2, NumberLong("2090845886852"), 23 ]
}]
←  $last (array operator)$let (aggregation) →
Give Feedback
© 2022 MongoDB, Inc.

About

  • Careers
  • Investor Relations
  • Legal Notices
  • Privacy Notices
  • Security Information
  • Trust Center
© 2022 MongoDB, Inc.