$bottomN (Bottom N Accumulator)

Last updated: 2026-10-09

$bottomN (Bottom N Accumulator)

$bottomN is an accumulator returning the N bottom documents (or expression values) per group by a specified sort order, available since MongoDB 5.2 — symmetric to $topN. Order comes from $group's sortBy; n can be constant or expression. Use it for per-group lowest-N or oldest-N records.

CategoryAccumulators
MongoDB Version5.2+
Example Languagemongosh (Shell)

📝 Syntax

{ $group: { _id: <key>, bottomN: { $bottomN: { sortBy: { <field>: <1 or -1> }, output: <expression>, n: <number> } } } }

Returns:Array of the N bottom values or documents per group

▶ Example

Run the commands below in your local mongosh (requires a running mongod):

// $bottomN: bottom 3 names per class
db.scores.aggregate([
  { $group: { _id: '$class', bottom3: { $bottomN: { sortBy: { score: 1 }, output: '$name', n: 3 } } } }
])

Output:

{ "_id": "A", "bottom3": ["Dave", "Eve", "Frank"] }

📌 Notes

More hands-on cases coming soon.

📚 Related Tutorials

❓ FAQ

QHow is the direction of $bottomN versus $topN set?
AThe sortBy direction decides it: ascending makes $bottomN take the lowest segment.
QCan n be dynamic?
AYes, n accepts an expression.
QDoes $bottomN return whole documents?
AOmit output for whole documents; specify output for selected fields.
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%

🙏 帮我们做得更好

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

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