如何获取文档数组中元素的数量 – MongoDB?
我有以下的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。
编辑:
根据其中一个答案,我将我的查询修改为以下内容:
答案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); });
您可以改为使用聚合查询:
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}); } });
这将导致您在一个文件,其中计数将有您的要求的结果
这可能需要编写一个聚合,因为您需要计算通过电子邮件分组的申请人数组的大小:
这里是等同的mongodb查询,返回期望的电子邮件与计数:
db.yourCollection.aggregate( [{$match:{"email" : "test@gmail.com"}}, {$project:{_id:0, email:1,totalEmails:{$size:"$applicants"}}}, {$group:{_id:"$email", count:{$sum:"$totalEmails"}}}])
这返回{ "_id" : "test@gmail.com", "count" : 6 }
您可能需要根据您的代码进行更改。
- 在MEAN堆栈中不推荐使用Mongoose的默认承诺库
- 如何用sinon.js将全局依赖项的新实例方法存留在nodejs中
- Node.js Mongoose静态函数没有被调用
- 不能NPM当需要在test / index.js中需要selenium-webdriver的testing时启动
- grunt.js(一个node.js构build工具)不会创build目录或文件。 是否与权限相关?
- PHP和Javascript之间是否有共同的encryption方法?
- javascript:ReferenceError:导出未定义
- 基于时间的javascript函数与setInterval
- 通过node.js v5.10.1获取“inheritance”错误