$top (Top Accumulator)
Last updated: 2026-10-09
$top (Top Accumulator)
$top is an accumulator returning the top document of a group per a specified sort order — the whole document, not a single field — available since MongoDB 5.2. The order comes from $group's sortBy, not input sequence, unlike $first. Use $topN for several.
| Category | Accumulators |
|---|---|
| MongoDB Version | 5.2+ |
| Example Language | mongosh (Shell) |
📝 Syntax
{ $group: { _id: <key>, top: { $top: { sortBy: { <field>: <1 or -1> }, output: <expression> } } } }
Returns:Top document of the group per the sortBy order
▶ Example
Run the commands below in your local mongosh (requires a running mongod):
// $top: highest price per item by sortBy
db.sales.aggregate([
{ $group: { _id: '$item', top: { $top: { sortBy: { price: -1 }, output: '$price' } } } }
])
Output:
{ "_id": "Pen", "top": 80 }
📌 Notes
- Requires MongoDB 5.2 or later
- Order comes from $group's sortBy, independent of input order
- output selects the expression; omit it to return the whole document
🏷️ Related Tags
💡 Related Cases
More hands-on cases coming soon.
📚 Related Tutorials
❓ FAQ
QWhat is the difference between $top and $first?
A$top takes the best by an explicit sort rule; $first follows input order.
QWhich version does $top require?
AMongoDB 5.2 or later.
QCan $top return the whole document?
AYes, omitting output returns the whole document.