Obtaining $group result with group count

后端 未结 2 1720
借酒劲吻你
借酒劲吻你 2020-12-14 16:20

Assuming I have a collection called \"posts\" (in reality it is a more complex collection, posts is too simple) with the following structure:

> db.posts.f         


        
2条回答
  •  孤城傲影
    2020-12-14 16:57

    1. Use $project to save tag and count into tmp
    2. Use $push or addToSet to store tmp into your data list.

    Code:

    db.test.aggregate(
        {$unwind: '$tags'}, 
        {$group:{_id: '$tags', count:{$sum:1}}},
        {$project:{tmp:{tag:'$_id', count:'$count'}}}, 
        {$group:{_id:null, total:{$sum:1}, data:{$addToSet:'$tmp'}}}
    )
    

    Output:

    {
        "result" : [
                {
                        "_id" : null,
                        "total" : 5,
                        "data" : [
                                {
                                        "tag" : "SOME",
                                        "count" : 1
                                },
                                {
                                        "tag" : "RANDOM",
                                        "count" : 2
                                },
                                {
                                        "tag" : "TAGS1",
                                        "count" : 1
                                },
                                {
                                        "tag" : "TAGS",
                                        "count" : 1
                                },
                                {
                                        "tag" : "SOME1",
                                        "count" : 1
                                }
                          ]
                  }
          ],
          "ok" : 1
    }
    

提交回复
热议问题