Obtaining $group result with group count

后端 未结 2 1701
借酒劲吻你
借酒劲吻你 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
    }
    
    0 讨论(0)
  • 2020-12-14 16:57

    I'm not sure you need the aggregation framework for this other than counting all the tags eg:

    db.posts.aggregate(
      { "unwind" : "$tags" },
      { "group" : {
          _id: { tag: "$tags" },
          count: { $sum: 1 }
      } }
    );
    

    For paginating through per tag you can just use the normal query syntax - like so:

    db.posts.find({tags: "RANDOM"}).skip(10).limit(10)
    
    0 讨论(0)
提交回复
热议问题