$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.

CategoryAccumulators
MongoDB Version5.2+
Example Languagemongosh (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

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.
Web-Tutorial.com

Web-Tutorial Tech Team

A team of developers maintaining programming tutorials. Each tutorial is written and reviewed by developers with expertise in that field. We work to keep our content accurate and reliable — if you spot an issue, please let us know.

100%

🙏 帮我们做得更好

我们是刚上线的编程教程站,几个人的小团队,精力有限。页面虽经检查,难免还有疏漏——链接失效、排版错乱、内容有误、语言生硬……

如果您发现了,麻烦告诉我们,我们会在收到反馈后第一时间进行修复,再次感谢您的光临 🙏