$last (Last Accumulator)

Last updated: 2026-10-09

$last (Last Accumulator)

$last is an accumulator returning a field from the last document of a group — symmetric to $first and equally order-dependent, so $sort first. Typical use: fetch the newest record per group. Also usable as a window operator in $setWindowFields.

CategoryAccumulators
MongoDB Version1.0+
Example Languagemongosh (Shell)

📝 Syntax

{ $group: { _id: <key>, last: { $last: "$field" } } }

Returns:Field value from the last document of the group (by input order)

▶ Example

Run the commands below in your local mongosh (requires a running mongod):

// $last: price of the latest record per item
db.sales.aggregate([
  { $sort: { date: 1 } },
  { $group: { _id: '$item', lastPrice: { $last: '$price' } } }
])

Output:

{ "_id": "Pen", "lastPrice": 50 }

📌 Notes

📚 Related Tutorials

❓ FAQ

QHow do I get the newest record per group?
A$sort ascending by time, then use $last in $group to grab the newest value.
QWhat happens if $last is unsorted?
AIt returns the last document in input order, which is usually meaningless.
QWhat is the difference between $last and $top?
A$top takes the best by a sort rule; $last takes the input-order tail. Different semantics.
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%

🙏 帮我们做得更好

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

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