18. Grouping Numeric Ranges with $bucket and $bucketAuto
$bucket groups documents into explicitly defined ranges. $bucketAuto attempts to create a requested number of buckets with approximately balanced document counts and data-dependent boundaries.
Use $bucket when boundaries have business meaning, such as fixed price bands. Use $bucketAuto for exploratory distributions. Consider how missing, null, and nonnumeric values are handled, and use a default bucket when appropriate for values outside configured boundaries.
Code Example
db.products.aggregate([
{
$bucket: {
groupBy: "$currentPrice",
boundaries: [0, 1000, 5000, 10000, 20000],
default: "outside-defined-ranges",
output: { productCount: { $sum: 1 }, averagePrice: { $avg: "$currentPrice" } }
}
},
{ $sort: { _id: 1 } }
]);Key Takeaways
- $bucket uses explicit boundaries.
- $bucketAuto chooses data-dependent boundaries.
- A default bucket can capture out-of-range values.
- Validate values before interpreting distributions.
Knowledge Check
Which operator is best when price bands must use fixed business thresholds?