【发布时间】:2016-09-01 00:02:51
【问题描述】:
我有以下 MongoDB 集合 (JSON):
{
"_id" : ObjectId("570185458351bbac27bc9a20"),
"email" : "test@gmail.com",
"applicants" : [
{
"id" : "570724e4ae4f8a5026156999",
"email" : "a@gmail.com",
},
{
"id" : "570724e4ae4f8a5026156333",
"email" : "a2@gmail.com",
},
{
"id" : "570724e4ae4f8a5026156111",
"email" : "a3@gmail.com",
},
{
"id" : "570724e4ae4f8a5026156222",
"email" : "a4@gmail.com",
}
],
},
{
"_id" : ObjectId("570185458351bbac27bc9a20"),
"email" : "test@gmail.com",
"applicants" : [
{
"id" : "570724e4ae4f8a5026156555",
"email" : "a@gmail.com",
},
{
"id" : "570724e4ae4f8a5026156666",
"email" : "a2@gmail.com",
},
],
},
{
"_id" : ObjectId("570185458351bbac27bc9a20"),
"email" : "test2@gmail.com",
"applicants" : [
{
"id" : "570724e4ae4f8a5026156555",
"email" : "a@gmail.com",
},
{
"id" : "570724e4ae4f8a5026156666",
"email" : "a2@gmail.com",
},
],
}
我想获取电子邮件 = test@gmail.com 的文档的所有数组中的元素计数。我该如何计算?
我正在使用以下内容通过电子邮件 test@gmail.com 获取文档数量:
collection.count({"email" : tmpEmail}, function (err, count) {
res.json(count);
console.log("Number: " + count);
});
如何继续计算电子邮件为 test@gmail.com 的文档的所有申请人数组中的元素数量?上面示例的可能是:6.
编辑:
根据其中一个答案,我将查询修改为以下内容:
答案 1:
collection.aggregate(
{$match: {"email": req.user.username, "status" : "true"}},
{$unwind: "$applicants"},
{$group: {_id:null, count: {$sum :1}}, function (err, count) {
res.json(count);
console.log("Number of New Applicants: " + count);
}
});
答案 2:
collection.aggregate(
[{$match:{"email" : req.user.username, "status" : "true"}},
{$project:{_id:0, email:1, totalApplicants:{$size:"$applicants"}}},
{$group:{_id:"$employer", count:{$sum:"$totalApplicants"}}}],
function (err, count){
res.json(count);
console.log("Number of New Applicants: " + count);
});
【问题讨论】:
标签: javascript node.js mongodb mongoose