How to Use $last in Aggregation in MongoDB: Syntax and Examples
$last operator to get the last value from a group of documents or sorted data. It returns the value of a specified field from the last document in the group or pipeline stage. Use it inside $group or $setWindowFields stages to capture the last element based on your sorting.Syntax
The $last operator is used inside aggregation stages like $group or $setWindowFields. It returns the value of the specified expression from the last document in the group or window.
$last: <expression>- Returns the value of the expression from the last document.
In $group, documents are grouped by a key, and $last returns the last value in the group based on the input order or after sorting.
{
$group: {
_id: <grouping_key>,
lastValue: { $last: <field_or_expression> }
}
}Example
This example groups sales by store and returns the last saleDate for each store. The documents are sorted by saleDate before grouping to ensure $last returns the latest date.
db.sales.aggregate([
{ $sort: { store: 1, saleDate: 1 } },
{ $group: {
_id: "$store",
lastSaleDate: { $last: "$saleDate" }
}
}
])Common Pitfalls
One common mistake is using $last without sorting the documents first. Since $last returns the last document in the input order, not sorting can lead to unexpected results.
Another pitfall is confusing $last with $max. $last returns the last document's value, while $max returns the maximum value.
/* Wrong: No sorting, so lastSaleDate may be incorrect */ db.sales.aggregate([ { $group: { _id: "$store", lastSaleDate: { $last: "$saleDate" } } } ]) /* Right: Sort by saleDate ascending before grouping */ db.sales.aggregate([ { $sort: { store: 1, saleDate: 1 } }, { $group: { _id: "$store", lastSaleDate: { $last: "$saleDate" } } } ])
Quick Reference
| Operator | Description | Usage Context |
|---|---|---|
| $last | Returns the value of the last document in a group or window | Inside $group or $setWindowFields |
| $first | Returns the value of the first document in a group or window | Inside $group or $setWindowFields |
| $max | Returns the maximum value in a group | Inside $group |
| $sort | Sorts documents to control order for $last or $first | Before $group stage |