$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.
| Category | Accumulators |
|---|---|
| MongoDB Version | 1.0+ |
| Example Language | mongosh (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
- Symmetric to $first with the same order dependence
- Idiomatic newest record: $sort ascending by time, then $last
- Works as a window operator in $setWindowFields
🏷️ Related Tags
💡 Related Cases
📚 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.