gpt4 book ai didi

javascript - 如何获取文档数组中元素的数量 - MongoDB?

转载 作者:行者123 更新时间:2023-11-30 08:31:39 24 4
gpt4 key购买 nike

我有以下 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",
},
],
}

我想获取 email = test@gmail.com 的文档的所有数组中元素的计数。我怎样才能得到那个计数?

我正在使用以下方法获取电子邮件 test@gmail.com 的文档数量:

   collection.count({"email" : tmpEmail},    function (err, count) {
res.json(count);
console.log("Number: " + count);
});

我如何继续计算电子邮件为 test@gmail.com 的文档的所有申请人数组中的元素数量?上面示例的可能是:6.

编辑:

根据其中一个答案,我将查询修改为以下内容:

答案一:

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);
});

最佳答案

您可以改用聚合查询:

collection.aggregate(
[{$match: {"email": req.user.username, "status" : "true"}},
{$unwind: "$applicants"},
{$group: {_id:null, count: {$sum :1}}}], function (err, result) {
console.log(result);
console.log("Number of New Applicants: " + result[0].count);
if(result.length > 0)
res.json(result[0]);
else
res.json({count:0});
}
});

这将生成一份文档,其中 count 将具有您所需的结果

关于javascript - 如何获取文档数组中元素的数量 - MongoDB?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37063483/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com