The $top accumulator picks the single highest-ranked document in each $group bucket using a sortBy specification—ideal for “best score,” “latest order,” or “highest price” reports.
01
One doc per group
Full record at top of sort.
02
sortBy required
Defines what “top” means.
03
output shape
$$ROOT or selected fields.
04
vs $max
Value only vs whole document.
05
vs $topN
One record vs N records.
06
MongoDB 5.2+
Part of $top/$bottom family.
Fundamentals
Definition and Usage
$top is a MongoDB accumulator used in the $group stage. It sorts documents within each group according to sortBy, then returns the document at the top of that ordering—the first document in the sorted list.
💡
Beginner tip
With sortBy: { score: -1 }, descending order puts the highest score at the top—so $top returns the student with the best score in each class. Use date: -1 when “top” should mean the most recent record.
Choose $top when you need identifying fields (name, id, date) from the winning record. Use $max when you only need the numeric maximum. Need multiple top-ranked rows? Use $topN.
Use both in the same $group when dashboards show the peak value and the record that achieved it.
Example 5 — Tie-break with secondary sort
When two students share the highest score, add a secondary key so ranking is predictable:
mongosh
db.scores.aggregate([
{
$group: {
_id: "$class",
topScorer: {
$top: {
output: { name: "$student", score: "$score" },
sortBy: { score: -1, student: 1 }
}
}
}
}
]);
// If Charlie and Chris both score 91, student: 1
// puts Charlie before Chris — Charlie wins the tie
📤 Tip:
Add sort fields until ties are broken—or use $topN to return all tied docs.
How It Works
Always add tie-breakers (name, timestamp, _id) when business rules require deterministic winners.
Compare
📋 $top vs related accumulators
Accumulator
Returns
sortBy
Best for
$top
One document
Required
Single top-ranked record
$topN
Array of N documents
Required
Top 3 leaderboard, etc.
$max
Maximum field value
Not used
Largest number only
$first / $last
First/last by input order
Not used
Insertion order (unstable without $sort)
$bottom
One bottom-ranked document
Required
Lowest score / earliest date
🧠 How $top Works
1
Documents bucketed
$group assigns each document to a group via _id.
Group
2
Sorted within group
sortBy ranks documents inside each bucket independently.
Sort
3
Top document selected
The first document in that sort order becomes the accumulator result.
Pick
=
🏆
output returned
The output expression shapes what fields appear in the final object.
Important
📝 Notes
$top requires MongoDB 5.2+—verify server version before deploying.
sortBy is mandatory—there is no default sort order.
Result is one document per group, not an array (use $topN for many).
Ties may pick an arbitrary winner unless you add secondary sortBy keys.
On older MongoDB, approximate with $sort + $group + $first patterns (less efficient).
$top answers “which single record is at the high end of my ranking?” inside each group. Define sortBy carefully, project with output, and add tie-breakers when duplicates matter.
Pair with $max for the numeric peak alone, or move to $topN when you need several top-ranked documents per bucket.
Always specify sortBy explicitly—match your business definition of “top”
Add secondary sort keys (student, _id) to break ties
Use $$ROOT when downstream stages need the full document
Put $match before $group to shrink working sets
Confirm MongoDB 5.2+ in staging before production rollout
❌ Don’t
Confuse $top with $topN (one doc vs array)
Expect $max to return student names—it only returns the maximum value
Rely on tie order without extra sortBy fields
Use on MongoDB versions before 5.2 without a fallback pipeline
Forget that sort direction changes which document is “top”
Summary
Key Takeaways
Knowledge Unlocked
Five things to remember about $top
Use these points when ranking documents inside $group.
5
Core concepts
🏆01
One document
Top of sort per group.
Basics
📦02
sortBy
Required ranking spec.
Syntax
👤03
vs $max
Doc vs scalar value.
Compare
📄04
$$ROOT
Return full record.
Pattern
🔢05
5.2+
Check server version.
Version
❓ Frequently Asked Questions
$top returns one document per $group—the document ranked first according to the sortBy order you specify. It is useful when you need the whole record (name, score, date), not just a single field value.
Inside the $group stage: { winner: { $top: { output: "$$ROOT", sortBy: { score: -1 } } } }. It requires both output and sortBy.
$max returns the largest value of one field (e.g. the number 91). $top returns an entire document—the student or order that sits at the top of your sort order.
$top returns exactly one top-ranked document. $topN returns N top documents as an array. Use $top when you only need the single best record per group.
$top was added in MongoDB 5.2 as part of the $top/$bottom accumulator family. Upgrade the server or use $sort + $first/$last patterns on older versions.
sortBy defines ranking within each group—same rules as $sort. Use { score: -1 } for highest score first (top = best score), or { date: -1 } for the most recent document at the top.
Did you know?
$top and $bottom were added together in MongoDB 5.2 to replace fragile $sort + $group + $first recipes for ranked group results. Before 5.2, developers often sorted the entire collection globally and hoped group order stayed correct—$top ranks inside each bucket independently. See the official $top docs.