'MongoDB Aggregating counts with different conditions at once

I'm totally new to MongoDB. I wonder if it is possible to aggregate counts with different conditions at once.

Such as, there is a collection like below.

_id  |  no  |  val |  
--------------------
 1   |   1  |   a  |
--------------------
 2   |   2  |   a  |
--------------------
 3   |   3  |   b  |
--------------------
 4   |   4  |   c  |
--------------------

And I want result like below.

  • Value a : 2
  • Value b : 1
  • Value c : 1

How can I get this result all at once?

Thank you:)



Solution 1:[1]

db.collection.aggregate([
  {
    "$match": {}
  },
  {
    "$group": {
      "_id": "$val",
      "count": { "$sum": 1 }
    }
  },
  {
    "$project": {
      "field": {
        "$arrayToObject": [
          [ { k: { "$concat": [ "Value ", "$_id" ] }, v: "$count" } ]
        ]
      }
    }
  },
  {
    "$replaceWith": "$field"
  }
])

mongoplayground

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 YuTing