How do I fill $bucketAuto ,granularity options?

this page, https://docs.mongodb.com/manual/reference/operator/aggregation/bucketAuto/
when I try example with:

db.artwork.aggregate([
   {
     $bucketAuto: {
       groupBy : "$year",
       buckets:3,
       granularity:"R5"
     }
   }
   ])

it return error :

MongoError: $bucketAuto can specify a ‘granularity’ with numeric boundaries only, but found a value with > type: missing

my mongodb version:

  • MongoDB shell version v4.0.0
  • MongoDB server version: 4.0.0

Hi @yang_xiaoyu,
Seems like some of your documents are missing the year field, can you please confirm that?

In case you have any doubts, please feel free to reach out to us.

Thanks and Regards.
Sourabh Bagrecha

You can filter those documents which have a year value first, and then bucketAuto.

@SourabhBagrecha @Vivek_Poddar
if I delete granularity , it works :

db.artwork.aggregate([
  {
    $bucketAuto: {
      groupBy : "$year",
      buckets:3
    }
  }
  ])
{ _id: { min: null, max: 1913 }, count: 3 }
{ _id: { min: 1913, max: 1926 }, count: 3 }
{ _id: { min: 1926, max: 1931 }, count: 2 }

Hi @yang_xiaoyu, it is the expected behavior of $bucketAuto with granularity.

As mentioned in the documentation under the field description table, that granularity option is:

Available only if all the groupBy values are numeric and none of them are NaN.

I hope it helps, for now, I would suggest you to filter out all the non-numeric and NaN values before the bucketAuto stage.

In case you have any doubts, please feel free to reach out to us.

Thanks and Regards.
Sourabh Bagrecha