$last
The `$last` operator sorts documents on one or more fields specified by the query and returns the last document matching the filtering criteria.
Syntax
{
$last: <expression>
}
Parameters
expression
objectrequiredThe expression to evaluate and return the last document from the result set.
Examples
Sample Data
{
"_id": "0fcc0bf0-ed18-4ab8-b558-9848e18058f4",
"name": "First Up Consultants | Beverage Shop",
"lastUpdated": "2024-12-31T13:01:19.097Z"
}
Get the last updated store within a company
Retrieve the most recently updated store by sorting in ascending order and taking the last document.
This query sorts stores by lastUpdated field and returns the last (most recent) update timestamp.
Query:
db.stores.aggregate([
{
$match: { company: { $in: ["First Up Consultants"] } }
},
{
$sort: { lastUpdated: 1 }
},
{
$group: {
_id: "$company",
lastUpdated: { $last: "$lastUpdated" }
}
}
])
Output:
[
{
"_id": "First Up Consultants",
"lastUpdated": "2024-12-31T13:01:19.097Z"
}
]
Using the window operator
Retrieve the most recently updated store within each company using window functions.
This query partitions by company and sorts within each partition to find the last update.
Query:
db.stores.aggregate([
{
$setWindowFields: {
partitionBy: "$company",
sortBy: { lastUpdated: 1 },
output: {
lastUpdatedDateForStore: {
$last: "$lastUpdated",
window: {
documents: ["current", "unbounded"]
}
}
}
}
}
])
Output:
[
{
"_id": "First Up Consultants",
"lastUpdated": "2024-12-31T13:01:19.097Z"
}
]