Search code examples
javascriptmongodbmongodb-queryaggregation-frameworkaggregate

Best aggregate approach regarding a query on 100k docs in a collection


if I have 100k docs in a collection like this:

{
    {
      userName: "cary"
      time: 50
      userId: 1
    }
    {
      userName: "john"
      time: 40
      userId: 1
    }
    {
      userName: "bliss"
      time: 50
      userId: 1
    }
    {
      userName: "ross"
      time: 40
      userId: 1
    }
    ...
    ...
    etc...
}

I have to query in this collection such as I will get the count of users whose time is less than 40,50,60 etc

result should look like this:

{
  time: UsersCountWithPrticularTime,
  ‘40’: 150,
  ‘50’: 50,
  ‘60’: 75,
  ‘40’: 90,
}

how can I achieve this?


Solution

  • I got the best optimize solution by using $bucket https://www.mongodb.com/docs/manual/reference/operator/aggregation/bucket/