$bucket (Bucket)
Last updated: 2026-10-09
$bucket (Bucket)
$bucket groups documents into buckets defined by an ascending boundaries array, emitting one { _id: lowerBound, count: N } document per bucket, with optional output accumulators. Documents outside all boundaries fall into the default bucket. Ideal for histograms and range statistics.
| Category | Grouping & Window |
|---|---|
| MongoDB Version | 1.0+ |
| Example Language | mongosh (Shell) |
📝 Syntax
{ $bucket: { groupBy: <expression>, boundaries: [ <lowerBound>, ... ], default: <value>, output: { <field>: <accumulator> } } }
⚙️ Parameters
| groupBy | Expression that determines which bucket a document falls into. |
|---|---|
| boundaries | Ascending bucket boundary array, at least two values. |
| default | Bucket name for documents outside all boundaries; omitted documents are dropped. |
| output | Accumulators computed per bucket, e.g. $avg or $sum. |
Returns:One { _id, count, ... } document per bucket
▶ Example
Run the commands below in your local mongosh (requires a running mongod):
// $bucket: bucket scores into ranges, average per bucket
db.scores.aggregate([
{ $bucket: {
groupBy: '$score',
boundaries: [0, 60, 80, 100],
default: 'other',
output: { avg: { $avg: '$score' } }
} }
])
Output:
{ "_id": 0, "count": 12, "avg": 35.5 }
{ "_id": 60, "count": 20, "avg": 71.2 }
📌 Notes
- boundaries must be ascending with at least two values
- Ranges are half-open: values fall into [boundaries[i], boundaries[i+1])
- Out-of-range documents go to default, or are dropped if it is omitted
🏷️ Related Tags
💡 Related Cases
📚 Related Tutorials
❓ FAQ
QWhat is the difference between $bucket and $bucketAuto?
A$bucket takes explicit boundaries; $bucketAuto splits buckets automatically for even counts.
QAre the ranges half-open?
AYes: values fall into [boundaries[i], boundaries[i+1]); the last boundary is an exclusive upper bound.
QCan the default bucket be omitted?
AYes; documents outside all buckets are then dropped.