- Reference >
- Operators >
- Aggregation Pipeline Operators >
- Group Accumulator Operators >
- $last (aggregation)
$last (aggregation)¶
On this page
Definition¶
-
$last
¶ Returns the value that results from applying an expression to the last document in a group of documents that share the same group by a field. Only meaningful when documents are in a defined order.
$last
is only available in the$group
stage.$last
has the following syntax:For more information on expressions, see Expressions.
Behavior¶
When using $last
in a $group
stage, the
$group
stage should follow a $sort
stage to
have the input documents in a defined order.
Example¶
Consider a sales
collection with the following documents:
The following operation first sorts the documents by item
and
date
, and then in the following $group
stage, groups
the now sorted documents by the item
field and uses the
$last
accumulator to compute the last sales date for each item:
The operation returns the following results: