Articles → MONGODB → $Bucketauto Aggregate Stage In Mongodb

$Bucketauto Aggregate Stage In Mongodb






Purpose





Syntax


{
  $bucketAuto: {
    groupBy: <expression>, // Expression to group by
    buckets: <number>,     // Number of buckets to create
    output: {              // Optional: Output specifications
      <outputField1>: { <accumulator expression1> },
      <outputField2>: { <accumulator expression2> },
      ...
    },
    granularity: <string> // Optional: granularity to use
  }
}



Example




Picture showing the sample document collection in mongodb




db.sales.aggregate([
  {
    $bucketAuto: {
      groupBy: "$quantity",
      buckets: 3,
      output: {
        averagePrice: { $avg: "$price" },
        count: { $sum: 1 }
      }
    }
  }
])



Output


Picture showing the output of $bucketauto aggregate stage in mongodb



Posted By  -  Karan Gupta
 
Posted On  -  Thursday, June 13, 2024

Query/Feedback


Your Email Id
 
Subject
 
Query/FeedbackCharacters remaining 250