【问题标题】:how to use aggregate for group and count in mongoose?如何在猫鼬中使用聚合进行分组和计数?
【发布时间】:2017-02-27 21:17:18
【问题描述】:

我的数据库中有 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

【问题讨论】:

    标签: json node.js mongoose


    【解决方案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
    }
    

    【讨论】:

    • 我们怎样才能得到总数?
    【解决方案2】:

    这是我对 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"}
          }
         }
       ])
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-03-04
      • 2020-07-26
      • 2015-08-21
      • 2018-01-30
      • 2015-02-27
      • 2017-06-06
      • 2016-06-12
      • 2021-05-30
      相关资源
      最近更新 更多