计数特定键:使用聚合在mongodb中的子文档级别上的文档中出现值

时间:2014-09-12 09:31:21

标签: mongodb aggregation-framework

使用聚合

计算特定键:mongodb中子文档级别文档中的值出现次数

示例

    {
    "comments" : [ 
    {
        "body" : "est laborum",
        "email" : "ZoROirXN@thUNmWmY.com",
        "author" : "Gisela Levin"
    }, 
    {
        "body" : "aborum",
        "email" : "eAYtQPfz@kVZCJnev.com",
        "author" : "Kayce Kenyon"
    }
     ]
    },
    {
    "comments" : [ 
    {
        "body" : " est laborum",
        "email" : "ZoROirXN@thUNmWmY.com",
        "author" : "Gisela Levin"
    }, 
    {
        "body" : "im id est laborum",
        "email" : "eAYtQPfz@kVZCJnev.com",
        "author" : "Kayce Kenyon"
      }
      ]

     }

我只是想知道查询来计算特定作者评论的次数

1 个答案:

答案 0 :(得分:1)

var author = "someone";

db.c.aggregate({
    $match : {
        "comments.author" : author
    }
}, {
    $unwind : "$comments"
}, {
    $match : {
        "comments.author" : author
    }
}, {
    $group : {
        _id : "$comments.author",
        count : {
            $sum : 1
        }
    }
});

count 就是答案。