Home > Enterprise >  how to get simple count & group by in MongoDB?
how to get simple count & group by in MongoDB?

Time:12-19

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?

CodePudding user response:

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.

  • Related