$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.

CategoryAccumulators
MongoDB Version5.2+
Example Languagemongosh (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

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.
Web-Tutorial.com

Web-Tutorial Tech Team

A team of developers maintaining programming tutorials. Each tutorial is written and reviewed by developers with expertise in that field. We work to keep our content accurate and reliable — if you spot an issue, please let us know.

100%

🙏 帮我们做得更好

我们是刚上线的编程教程站,几个人的小团队,精力有限。页面虽经检查,难免还有疏漏——链接失效、排版错乱、内容有误、语言生硬……

如果您发现了,麻烦告诉我们,我们会在收到反馈后第一时间进行修复,再次感谢您的光临 🙏