The $topN accumulator collects the N highest-ranked documents in each $group bucket—perfect for top-3 leaderboards, best-selling products, or latest orders when one record is not enough.
01
N docs per group
Array of top-ranked records.
02
n + sortBy + output
Three required properties.
03
Flexible output
Project fields or use arrays.
04
vs $top
Many records vs one record.
05
Short groups OK
Returns all docs if fewer than N.
06
MongoDB 5.2+
Part of $top/$bottom family.
Fundamentals
Definition and Usage
$topN is a MongoDB accumulator used in the $group stage. It sorts documents within each group using sortBy, then returns the first N documents in that ordering as an array.
💡
Beginner tip
To get the three highest scores, use sortBy: { score: -1 } (descending). The biggest numbers sort first—PlayerC (99), PlayerB (33), PlayerA (31) fill the top three slots in game G1.
Choose $topN when dashboards need a leaderboard slice (top 5 sellers, 3 fastest response times). Use $top when only the single best record matters, or $bottomN for the bottom of the ranking.
Foundation
📝 Syntax
$topN requires an object with n, sortBy, and output:
$topN answers “which N records sit at the high end of my ranking?” inside each group. Set n, define ranking with sortBy, and shape results with output.
Pair with $top for the single best record, or explore $firstN when input order matters instead of explicit in-group ranking.
Document your sortBy choice—“top” follows sort order, not intuition alone
Use sortBy: { score: -1 } for highest numeric scores (MongoDB official pattern)
Add secondary sort keys (playerId, _id) to break ties
Put $match before $group to reduce data processed per bucket
Test with groups smaller than n to confirm array length behavior
❌ Don’t
Confuse $topN with $top (array vs single object)
Assume ascending sort always means “highest score”—use descending for max-first rankings
Expect $max or $maxN to return player names—they return values only
Use on MongoDB versions before 5.2 without a fallback pipeline
Forget the 100 MB per-group memory cap on very large buckets
Summary
Key Takeaways
Knowledge Unlocked
Five things to remember about $topN
Use these points when building top-k reports inside $group.
5
Core concepts
🏅01
Array of N
Top-ranked docs per group.
Basics
🔢02
n key
How many to collect.
Syntax
🏆03
sortBy
Defines top ranking.
Ranking
👤04
vs $top
Many vs one record.
Compare
📄05
5.2+
Check server version.
Version
❓ Frequently Asked Questions
$topN returns an array of the N documents ranked at the top of each $group bucket according to sortBy. Use it for top-3 scorers, highest-priced products, or latest N orders—when you need more than one best record.
$top returns exactly one top-ranked document (a single object). $topN returns up to N documents as an array. Use $top for the single best record; use $topN for a leaderboard or top-k list.
Use sortBy: { score: -1 } (descending)—highest scores sort first and land in the top N slots. For most recent records, use sortBy: { date: -1 }. Always match sortBy to your business definition of top.
$topN returns all documents in the group—never more than exist. If a class has only two students and n is 3, you get an array of two items.
$topN was added in MongoDB 5.2 alongside $top, $bottom, and $bottomN. On older servers, approximate with $sort + $group patterns (less efficient).
Did you know?
$topN can use a dynamic n expression based on the group _id—handy when one pipeline must return different leaderboard sizes per category. Before MongoDB 5.2, developers built top-k lists with $sort, $group, and $push + $slice. See the official $topN docs.