- Reference >
- Operators >
- Aggregation Pipeline 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 output
value depends on the order of the documents coming into pipeline. To
guarantee a defined order, the $group
pipeline stage should
follow a $sort
stage.
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: