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




AttributeDescription
groupByThe field or expression used for grouping.
boundariesAn array of values that define the boundaries for the buckets. The array must be sorted in ascending order and contain at least two values.
defaultThe container for values outside the specified boundaries.
outputA document that defines 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