Using 2 $count in one query

Viewed 19

I have the following collection:

{'user': 'Emma', 'type': 'Apple'}
{'user': 'Emma', 'type': 'Orange'}
{'user': 'Emma', 'type': 'Orange'}

I want to get statistics for "Emma", How many records of "apples" and "oranges" there are.

For example the output:

{
    'apple': 1,
    'Orange': 1
}

It's very simple to do this if I split it into 2 queries. But for efficiency, I want to do it all at once.

I'm wondering if I should use $facet.

1 Answers
  • $match user condition
  • $group by type and get count
  • $group by null and construct the array of type and count in key-value format
  • $arrayToObject convert above key-value array to object
  • $replaceRoot to replace above converted object to root
db.collection.aggregate([
  { $match: { user: "Emma" } },
  {
    $group: {
      _id: "$type",
      count: { $sum: 1 }
    }
  },
  {
    $group: {
      _id: null,
      types: { $push: { k: "$_id", v: "$count" } }
    }
  },
  { $replaceRoot: { newRoot: { $arrayToObject: "$types" } } }
])

Playground

Related