如何使用聚合组和计数猫鼬?

时间:2016-10-18 14:27:52

标签: json node.js mongoose

我的数据库中有json对象,如下所示:

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

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

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

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

我正在尝试获得如下输出

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

我使用了聚合查询。

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

我的输出为

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

现在我有疑问,我怎么能得到比赛的数量。它目前的板球示例是2,对于test1用户的足球1

2 个答案:

答案 0 :(得分:1)

类似的问题是answered

对于您的特定情况,它将是:

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" } } 
    }
  }
 ])

结果应如下:

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

答案 1 :(得分:1)

以下是 test1 名称记录的解决方案

    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"}
      }
     }
   ])