0

My sample data is:

[{
  "company": "apple",
  "last_view": "2020-01-01"
}, {
  "company": "google",
  "last_view": "2020-01-01"
}, {
  "company": "google",
  "last_view": "2020-01-01"
}]

Now to group this data based on company and different group by based on last_view I should have:

{
"companies": [{
  "_id": "google",
  "count": 2,
}, {
  "_id": "apple",
  "count": 1
}],
"last_views": [{
  "_id": "2020-01-01",
  "count": 3
}]
}

Using facets in Mongo I can have multiple stages but it seems that I need to use bucket. bucket is used to group by numerical data with boundaries which in my case they do not have boundaries. Using a normal group by is like below:

{
  "$group": {
    "_id": "$company",
    "count": {
      "$sum": 1
    }
  }
}

How can I have multiple groupBy in MongoDB?

  • You can use facets. Within one aggregation you can have two facets; one to group by company and the other to group by the last_view field. – prasad_ Mar 18 at 9:51

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Browse other questions tagged or ask your own question.