user2993539
user2993539

Reputation: 495

how to get simple count & group by in MongoDB?

assuming I have a data that has two categories, for example - football or basketball, where football value is 1 and basketball value is 2, and we have the following data:

_id    game
'1'      1
'2'      1
'3'      2
'4'      1
'5'      2

(the data contains football 3 times and basketball 2 times). I want to perform an aggregation that returns the following object:

{
   footballCount: 3,
   basketballCount: 2
}

I can't think of such an aggregation that results in such structure. How can I do that?

Upvotes: 0

Views: 117

Answers (1)

ray
ray

Reputation: 15217

You can do a conditional sum for different cases.

db.collection.aggregate([
  {
    $group: {
      _id: null,
      footballCount: {
        $sum: {
          "$cond": {
            "if": {
              $eq: [
                "$game",
                1
              ]
            },
            "then": 1,
            "else": 0
          }
        }
      },
      basketballCount: {
        $sum: {
          "$cond": {
            "if": {
              $eq: [
                "$game",
                2
              ]
            },
            "then": 1,
            "else": 0
          }
        }
      }
    }
  }
])

Here is the Mongo playground for your reference.

Upvotes: 1

Related Questions