Articles → MONGODB → $Bucket Aggregation Operator In Mongodb
$Bucket Aggregation Operator In Mongodb
Purpose
Syntax
{
$bucket: {
groupBy: <expression>,
boundaries: [ <lower bound>, <upper bound> ],
default: <value>,
output: {
<output1>: { <accumulator1> },
...
}
}
}
- groupBy → The field or expression to group by
- boundaries → An array of values that specify the boundaries for the buckets. The array must be sorted in ascending order and contain at least two values
- default → The bucket for values that do not fit in the specified boundaries
- default → A document that specifies the output for each bucket. You can use aggregation expressions and accumulators like $sum, $avg, $max, etc.
Example
db.sales.aggregate([
{
$bucket: {
groupBy: "$price",
boundaries: [0, 10, 20, 30],
default: "Other",
output: {
Sum: { $sum: 1}
}
}
}
])
Output