$topN (Top N Accumulator)
Last updated: 2026-10-09
$topN (Top N Accumulator)
$topN is an accumulator returning the N top documents (or expression values) per group by a specified sort order, available since MongoDB 5.2. Order comes from $group's sortBy; n can be a constant or expression. Great for leaderboards and per-group top lists.
| Category | Accumulators |
|---|---|
| MongoDB Version | 5.2+ |
| Example Language | mongosh (Shell) |
📝 Syntax
{ $group: { _id: <key>, topN: { $topN: { sortBy: { <field>: <1 or -1> }, output: <expression>, n: <number> } } } }
Returns:Array of the N top values or documents per group
▶ Example
Run the commands below in your local mongosh (requires a running mongod):
// $topN: top 3 names per class
db.scores.aggregate([
{ $group: { _id: '$class', top3: { $topN: { sortBy: { score: -1 }, output: '$name', n: 3 } } } }
])
Output:
{ "_id": "A", "top3": ["Alice", "Bob", "Carol"] }
📌 Notes
- Requires MongoDB 5.2 or later
- n accepts an expression, so it can be dynamic
- Ties in sortBy are not deterministic in result order
🏷️ Related Tags
💡 Related Cases
More hands-on cases coming soon.
📚 Related Tutorials
❓ FAQ
QCan $topN's n be a variable?
AYes, n can be an expression referencing a field, e.g. '$limitCount'.
QHow does $topN differ from $sort plus $limit?
A$topN takes the top N within each group; $sort plus $limit takes the top N of the whole stream.
QHow are ties handled?
ATied elements are unordered; use a unique sort key for stability.