$lastN (Last N Accumulator)
Last updated: 2026-10-09
$lastN (Last N Accumulator)
$lastN is an accumulator returning an array of a field's values from the last N documents of a group (in input order), available since MongoDB 5.2 — symmetric to $firstN. Often used to fetch the newest N records per group; order-dependent, so $sort first. n can be constant or expression.
| Category | Accumulators |
|---|---|
| MongoDB Version | 5.2+ |
| Example Language | mongosh (Shell) |
📝 Syntax
{ $group: { _id: <key>, lastN: { $lastN: { input: <expression>, n: <number> } } } }
Returns:Array of expression values from the last N documents of the group
▶ Example
Run the commands below in your local mongosh (requires a running mongod):
// $lastN: prices of the latest 3 records per item
db.sales.aggregate([
{ $sort: { date: 1 } },
{ $group: { _id: '$item', last3: { $lastN: { input: '$price', n: 3 } } } }
])
Output:
{ "_id": "Pen", "last3": [50, 55, 60] }
📌 Notes
- Requires MongoDB 5.2 or later
- Order depends on input; $sort before grabbing the newest
- n accepts an expression for dynamic counts
🏷️ Related Tags
💡 Related Cases
More hands-on cases coming soon.
📚 Related Tutorials
❓ FAQ
QHow do I get the newest N per group?
A$sort ascending by time, then use $lastN inside $group.
QWhat is the difference between $lastN and $bottomN?
A$lastN takes the input-order tail; $bottomN takes the worst N by a sortBy rule.
QWhat if I do not sort?
AThe result is meaningless — just the input-order tail.