Chapter 4 Core Aggregation - Multidimensional grouping - $bucketAuto

Hi,
In the quiz question of Facets: Auto Buckets section of this chapter, the last option
count only documents that contain **groupBy** field defined in the documents should also be in the correct options, right? This, since groupBy is the main criteria for filtering documents. If that particular field was not defined in the document, how would the pipeline consider it to be put in one of the buckets?

Thanks,
Apurva.

Hi,

No, that option is not correct. It also counts the documents which do not include the groupBy field. In such a case, null is used as its value. Hope this example helps:

db.testing.insertMany([
   {price: 19, type: 1},
   {price: 19, type: 2},
   {price: 15, type: 2},
   {price: 15, type: 3},
   {price: 5, type: 4},
   {price: 51, type: 4},
   {price: 7, type: 4},
   {price: 70, type: 1},
   {price: 70, type: 2},
   {type: 2}
])


db.testing.aggregate([{
   $bucketAuto: {
      groupBy: "$price", buckets: 5
   }
}])

{ "_id" : { "min" : null, "max" : 7 }, "count" : 2 }

{ "_id" : { "min" : 7, "max" : 19 }, "count" : 3 }

{ "_id" : { "min" : 19, "max" : 51 }, "count" : 2 }

{ "_id" : { "min" : 51, "max" : 70 }, "count" : 3 }

José Carlos

1 Like

Oh, Okay! This clears a lot.

Thanks.

You are welcome!

José Carlos