Introduction
These accumulators help you pick the first or last value from a group of data. They are useful when you want to find the earliest or latest item in a list.
These accumulators help you pick the first or last value from a group of data. They are useful when you want to find the earliest or latest item in a list.
{ $group: { _id: <grouping_key>, firstValue: { $first: <expression> }, lastValue: { $last: <expression> } } }{ $group: { _id: "$category", firstProduct: { $first: "$product" } } }{ $group: { _id: "$user", lastLogin: { $last: "$loginDate" } } }This query sorts sales by date ascending, then groups by product. It finds the first and last sale date for each product.
db.sales.aggregate([
{ $sort: { date: 1 } },
{ $group: {
_id: "$product",
firstSaleDate: { $first: "$date" },
lastSaleDate: { $last: "$date" }
}
}
])Always sort your data before using $first or $last to get meaningful results.
If you do not sort, the first and last values depend on the natural order of documents, which may be unpredictable.
$first and $last pick the first or last value in a group.
Use $sort before $group to control which values are first or last.
They help summarize data by earliest or latest values.
$first accumulator do in a MongoDB aggregation pipeline?$first accumulator returns the first value of a specified field from documents in a group.$last, which returns the last value, $first picks the earliest value based on the document order.$first = first value [OK]$last in a MongoDB aggregation $group stage?$last accumulator must be used with a field path as a string, like "$item".$last: "$item" inside $group. Options A and C have syntax errors, and B uses $first instead of $last.sales with documents:{ "_id": 1, "product": "A", "date": "2023-01-01" },
{ "_id": 2, "product": "A", "date": "2023-01-05" },
{ "_id": 3, "product": "B", "date": "2023-01-02" }[
{ $sort: { date: 1 } },
{ $group: { _id: "$product", firstSale: { $first: "$date" }, lastSale: { $last: "$date" } } }
]$last values:db.orders.aggregate([
{ $group: { _id: "$customer", lastOrder: { $last: "$orderDate" } } }
])$last accumulator returns the last value in the current document order within each group.orderDate, documents are in arbitrary order, so $last may not return the latest date.orderDate before grouping. -> Option Aevents with documents:{ "user": "Alice", "timestamp": 100 },
{ "user": "Alice", "timestamp": 200 },
{ "user": "Bob", "timestamp": 150 },
{ "user": "Bob", "timestamp": 50 }timestamp: 1 ensures earliest events come first for each user.$first and $last after sorting picks the earliest and latest timestamps correctly.Pass the test and this pattern moves unknown