- Reference >
- Operators >
- Aggregation Pipeline Operators >
- $last (aggregation accumulator)
$last (aggregation accumulator)¶
On this page
Definition¶
-
$last¶
Changed in version 5.0.
Returns the value that results from applying an expression to the last document in a group of documents. Only meaningful when documents are in a defined order.
$last is available in these stages:
$bucket$bucketAuto$group$setWindowFields(Available starting in MongoDB 5.0)
Note
Disambiguation
This page describes the $last aggregation accumulator. For
the $last array operator, see $last (array
operator).
Behavior¶
To define the document order for $last with the:
$groupstage, add a$sortstage before the$groupstage.$setWindowFieldsstage, set the sortBy field.
Note
Although the $sort stage passes ordered documents as
input to the $group and $setWindowFields
stages, those stages are not guaranteed to maintain the sort order in
their own output.
When used with $setWindowFields, $last returns null
for empty windows. An example empty
window is a { documents: [ -1, -1 ] } documents window on the first document of a
partition.
Examples¶
Use in $group Stage¶
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:
Use in $setWindowFields Stage¶
New in version 5.0.
Create a cakeSales collection that contains cake sales in the states
of California (CA) and Washington (WA):
This example uses $last in the $setWindowFields
stage to output the last cake sales order type for each state:
In the example:
partitionBy: "$state"partitions the documents in the collection bystate. There are partitions forCAandWA.sortBy: { orderDate: 1 }sorts the documents in each partition byorderDatein ascending order (1), so the earliestorderDateis first.outputsets thelastOrderTypeForStatefield to the last ordertypefrom the documents window.The window contains documents between the
currentlower limit, which is the current document in the output, and theunboundedupper limit. This means$lastreturns the last ordertypefor the documents between the current document and the end of the partition.
In this output, the last order type value for CA and WA is
shown in the lastOrderTypeForState field: