$first (First Accumulator)
Last updated: 2026-10-09
$first (First Accumulator)
$first is an accumulator returning a field from the first document of a group. It depends on input order, so $sort before $group (or $group's sortBy since MongoDB 5.2) matters. It also works as a window operator in $setWindowFields.
| Category | Accumulators |
|---|---|
| MongoDB Version | 1.0+ |
| Example Language | mongosh (Shell) |
📝 Syntax
{ $group: { _id: <key>, first: { $first: "$field" } } }
Returns:Field value from the first document of the group (by input order)
▶ Example
Run the commands below in your local mongosh (requires a running mongod):
// $first: price of the earliest record per item
db.sales.aggregate([
{ $sort: { date: 1 } },
{ $group: { _id: '$item', firstPrice: { $first: '$price' } } }
])
Output:
{ "_id": "Pen", "firstPrice": 20 }
📌 Notes
- Order comes from the input; $sort before $group
- $group supports sortBy since MongoDB 5.2
- Usable as a window operator in $setWindowFields
🏷️ Related Tags
💡 Related Cases
Introduction to Aggregate Pipelines: The `aggregate` Method and the Basic Stage
$lookup and Associations with Multiple Sets
📚 Related Tutorials
❓ FAQ
QHow is $first order guaranteed?
A$sort before $group, or use sortBy inside $group on MongoDB 5.2 and later.
QWhat is the difference between $first and $min?
A$first takes the first document in input order; $min takes the smallest value regardless of order.
QWhat about empty groups?
AEmpty groups are never created; $group emits only real groups.