$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.
| Category | Accumulators |
|---|---|
| MongoDB Version | 5.2+ |
| Example Language | mongosh (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
- Requires MongoDB 5.2 or later
- Symmetric to $topN; direction is controlled by sortBy
- n accepts an expression for dynamic counts
🏷️ Related Tags
💡 Related Cases
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.