使用聚合
计算特定键: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"
}
]
}
我只是想知道查询来计算特定作者评论的次数
答案 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 就是答案。