Prashant Tapase
Prashant Tapase

Reputation: 2147

how to use aggregate for group and count in mongoose?

I have json object in my db like as follows:

{
'name':'test1',
'game':'cric'
},

{
'name':'test1',
'game':'cric'
},

{
'name':'test1',
'game':'football'
},

{
'name':'test2'
'game':'football'
}

I am trying to get output as follows

 {
    'name':'test1'
    'game':[{cric: 2}, {football:1}],
    'totalCount': 3
    }

I used aggregate query for that.

group {'_id':{name:'$name'}, {game:{$addToSet:$game}}
project {name : $name, game: $game}

I got output as

{name: 'test1', 'game':[cric, football]}

Now i have question that, how can i get count of game. it current example for cricket it is 2 and for football 1 for test1 user

Upvotes: 0

Views: 3038

Answers (2)

Anish Agarwal
Anish Agarwal

Reputation: 1821

Here is my solution to test1 name record

    db.getCollection('COLLECTION_NAME').aggregate([
      {$match : {name : "test1"}},
      {
        $group: {
         _id:  "$game" ,
         total: { "$sum": 1 },
         name :  {$first : "$name"}
        }
      },
      {
       $group: {
        _id : "$name",
        games: { $addToSet: { game: "$_id", sum:"$total" } },
        totalCount : {$sum : "$total"}
      }
     }
   ])

Upvotes: 1

Talha Awan
Talha Awan

Reputation: 4619

A similar question is answered here.

For your particular case it would be:

db.collection.aggregate([
  {
    $group: {
      _id:   { name: "$name", game: "$game" },
               games: { "$push": "$game" },
      total: { "$sum": 1 }
    }
  },
  {
    $group: {
      _id: { name: "$_id.name" },
      games: { $addToSet: { game: "$_id.game", sum:"$total" } } 
    }
  }
 ])

And the result should look like:

{
    "result" : [ 
        {
            "_id" : {
                "name" : "test1"
            },
            "games" : [ 
                {
                    "game" : "cric",
                    "sum" : 2
                }, 
                {
                    "game" : "football",
                    "sum" : 1
                }
            ]
        }, 
        {
            "_id" : {
                "name" : "test2"
            },
            "games" : [ 
                {
                    "game" : "football",
                    "sum" : 1
                }
            ]
        }
    ],
    "ok" : 1
}

Upvotes: 1

Related Questions