Discover how MongoDB's $first and $last can save you hours of tedious data searching!
Why $first and $last accumulators in MongoDB? - Purpose & Use Cases
Imagine you have a big list of customer orders sorted by date, and you want to find the very first and last order each customer made.
Doing this by hand means scanning through all orders for each customer, remembering the earliest and latest dates, and writing it down.
Manually checking each order is slow and tiring, especially when the list is huge.
It's easy to make mistakes, like missing an order or mixing up dates.
Also, updating the results when new orders come in means repeating the whole process again.
The $first and $last accumulators in MongoDB let you quickly grab the first and last items in a group during aggregation.
This means MongoDB does the hard work for you, scanning and picking the right records efficiently.
for each customer: earliest = None latest = None for order in orders: if order.customer == customer: if earliest is None or order.date < earliest: earliest = order.date if latest is None or order.date > latest: latest = order.date
[
{ $sort: { customer: 1, date: 1 } },
{ $group: {
_id: "$customer",
firstOrder: { $first: "$order" },
lastOrder: { $last: "$order" }
}
}
]You can instantly find the first and last records in any group, making data summaries and reports fast and reliable.
A store wants to know each customer's first and last purchase to send personalized offers and understand buying habits.
Manually finding first and last items is slow and error-prone.
$first and $last do this automatically during aggregation.
This saves time and ensures accurate results on large datasets.