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> },
      ...
    }
  }
}




  1. groupBy → The field or expression to group by
  2. 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
  3. default → The bucket for values that do not fit in the specified boundaries
  4. default → A document that specifies the output for each bucket. You can use aggregation expressions and accumulators like $sum, $avg, $max, etc.

Example




Picture showing the sample document collection




db.sales.aggregate([
  {
    $bucket: {
      groupBy: "$price",
      boundaries: [0, 10, 20, 30],
      default: "Other",
      output: {
        Sum: { $sum: 1}
      }
    }
  }
])



Output


Picture showing the output of $bucket aggregation operator in mongodb







Posted By  -  Karan Gupta
 
Posted On  -  Monday, June 10, 2024

Query/Feedback


Your Email Id
 
Subject
 
Query/FeedbackCharacters remaining 250