Aggregation $bucket
$bucket sorts documents into ranges of a value (price bands, age groups, order sizes) and computes accumulators for each range. It is the aggregation version of a histogram.
{ $bucket: {
groupBy: '<expression>', // the value to bucket
boundaries: [b0, b1, b2, …], // sorted lower bounds: [b0, b1), [b1, b2), …
default: '<bucket id>', // optional: for values outside the boundaries
output: { <field>: { <accumulator> }, … } // optional: default is { count: { $sum: 1 } }
} }Each bucket includes its lower boundary and excludes the upper one. The _id of a bucket is its lower boundary.
Price bands
print(db.products.aggregate([
{ $bucket: {
groupBy: '$price',
boundaries: [0, 10, 20, 50, 100]
} }
]).toArray());[
{ _id: 0, count: 7 },
{ _id: 10, count: 5 },
{ _id: 20, count: 6 },
{ _id: 50, count: 2 }
]
So 7 products cost under $10, 5 cost from $10 up to (not including) $20, 6 from $20 to under $50 and 2 from $50 to under $100. Without output, each bucket just has a count.
Custom output fields
print(db.products.aggregate([
{ $bucket: {
groupBy: '$price',
boundaries: [0, 10, 20, 50, 100],
output: {
products: { $sum: 1 },
names: { $push: '$name' },
avgRating: { $avg: '$rating' }
}
} },
{ $match: { _id: { $gte: 50 } } },
{ $set: { avgRating: { $round: ['$avgRating', 2] } } }
]).toArray());[
{
_id: 50,
products: 2,
names: [ 'Burr Grinder', 'Gooseneck Kettle' ],
avgRating: 4.65
}
]
Values outside the boundaries: default
If a value falls below the first boundary or at/above the last, $bucket fails, unless you give a default bucket to collect those values:
const pipeline = (extra) => [{ $bucket: { groupBy: '$total', boundaries: [0, 40, 80], ...extra } }];
try {
db.orders.aggregate(pipeline({})).toArray();
} catch (err) {
print('error code', err.code);
}
print(db.orders.aggregate(pipeline({ default: '80+' })).toArray());error code 7158303
[
{ _id: 0, count: 6 },
{ _id: 40, count: 11 },
{ _id: '80+', count: 3 }
]
Automatic buckets: $bucketAuto
If you don't want to choose boundaries yourself, $bucketAuto splits the values into a given number of buckets with roughly equal counts:
db.orders.aggregate([
{ $bucketAuto: { groupBy: '$total', buckets: 4 } }
]).forEach(b => print(b._id.min, '-', b._id.max, ':', b.count));11.5 - 37 : 5
37 - 49 : 5
49 - 71 : 5
71 - 121 : 5
Each bucket's _id is a { min, max } document. The last max is inclusive.
Labelled buckets with $switch
When you want readable labels instead of numbers, $group on a $switch expression is often simpler:
print(db.customers.aggregate([
{ $group: {
_id: { $switch: {
branches: [
{ case: { $lt: ['$joined', ISODate('2026-02-01T00:00:00Z')] }, then: 'January' },
{ case: { $lt: ['$joined', ISODate('2026-04-01T00:00:00Z')] }, then: 'Feb-Mar' }
],
default: 'April or later'
} },
customers: { $sum: 1 }
} },
{ $sort: { customers: -1, _id: 1 } }
]).toArray());[
{ _id: 'Feb-Mar', customers: 5 },
{ _id: 'April or later', customers: 4 },
{ _id: 'January', customers: 3 }
]
Test yourself
With boundaries: [0, 10, 20], which bucket gets the value 10?
- The bucket with _id 0
- The bucket with _id 10
- Both
- Neither: it's an error
What happens to a value of 250 with boundaries: [0, 100, 200] and no default?
- It goes into the last bucket
- It is ignored
- The aggregation fails
- A new bucket is created