MongoDB获得不喜欢用户的数量?

时间:2014-03-10 09:57:41

标签: mongodb

{
    "_id": ObjectId("531d68dab0b80560100dd205"),
    "id": 47,
    "userId": "2",
    "content": "Like Check ",
    "datetime": "2014/03/10",
    "parent": null,
    "files": [
        ObjectId("531d68dab0b80560100dd203")
    ],
    "category": null,
    "comments": [

    ],
    "type": null,
    "likes": [
         "4",
        "4",
        "6",
        "12",
        "1"
    ],
    "recipients": [
        "4",
        "4",
        "6",
        "12",

    ]
}

我有一个名为posts的集合,我需要从该集合中找出所喜欢的用户数量。请帮忙。 我在MongoDB终端上尝试过以下代码。

db.posts.aggregate([{$unwind : "$likes"}, {$group: { _id:null, number :{$sum :1}}}])

但结果是{ "result" : [ ], "ok" : 1 }

1 个答案:

答案 0 :(得分:2)

你应该这样写:

db.posts.aggregate([
  {$project: {"likes" :1}},
  {$unwind : "$likes" },
  {$group: {"_id": "$_id", count: {$sum: 1}}}
])

结果:

{
    "result" : [ 
        {
            "_id" : ObjectId("531d68dab0b80560100dd205"),
            "count" : 5
        }
    ],
    "ok" : 1
}