- Reference >
- Operators >
- Aggregation Pipeline Operators >
- $last (aggregation accumulator)
$last (aggregation accumulator)¶
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.Disambiguation
The following page describes the accumulator
$last
, available only within the$group
stage. For the array operator$last
, see$last (array operator)
instead.
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: