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

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

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

🙏 帮我们做得更好

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

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