$first, $last, and $top/$bottom Accumulators
Learners will pick the first or last document per group and use the newer $top and $bottom accumulators to pick by a sort key.
Picking One Document Per Group
Sometimes aggregation needs to select a single representative document from each group rather than computing a numeric aggregate. MongoDB provides several accumulators for this: $first, $last, and the newer $top and $bottom accumulators. Each has different semantics for determining which document is selected, and choosing the right one affects both correctness and performance.
$first: Taking the Earliest Document Value
$first returns the value from the first document encountered in the group. Since MongoDB does not guarantee document processing order within a $group unless you sort first, $first is meaningful only when you place a $sort stage immediately before the $group. This two-stage pattern—sort then group—is the standard way to reliably pick the earliest or highest-priority item per group.
db.orders.aggregate([
// Sort by date ascending so $first gets the oldest order
{ $sort: { createdAt: 1 } },
{
$group: {
_id: '$customerId',
firstOrderDate: { $first: '$createdAt' },
firstOrderAmount: { $first: '$amount' },
firstOrderId: { $first: '$_id' }
}
}
])All lessons in this course
- $sum, $avg, $min, $max: Numeric Aggregation
- $push and $addToSet: Building Arrays in Groups
- $first, $last, and $top/$bottom Accumulators
- Window Functions With $setWindowFields