我使用以下两种方法来按状态获取某些文档的计数。这是我的两种方法:-
collection.find({ Status: 'pending' }).count(function (e, pending) {
collection.find({ Status: 'open' }).count(function (e, open) {
collection.find({ Status: 'solved' }).count(function (e, solved) {
var obj={
solved:solved,
open:open,
pending:pending
}
res.send(obj);
});
});
});
第二个是:-
collection.find().toArray(function(e,data){
var open=data.filter(function(f){f.Status="open"}).length;
var solved=data.filter(function(f){f.Status="solved"}).length;
var pending=data.filter(function(f){f.Status="pending"}).length;
var obj={
solved:solved,
open:open,
pending:pending
}
res.send(obj);
});
我有一个循环将运行此代码 5 次(这只是实际的示例代码,我还有一些基于循环的其他条件)并返回结果。 但我不知道哪种方法更好。请帮助我选择对性能更好的最佳方式。 谢谢
最佳答案
这里需要在带宽和延迟之间进行权衡。
第一个创建 3 个数据库查询,这意味着从应用程序到数据库再返回 3 次网络往返。但是,每次往返仅返回一个数字。
第二个只有一次往返,但它下载了集合的全部内容。
哪种解决方案更好取决于您的网络基础设施及其提供的延迟和带宽。
但是,还有另一种方法可以让您两全其美,那就是使用聚合管道来计算数据库中所有字段的计数。这是一个未经测试的示例:
db.collection.aggregate([
// first project each document into a new one with separate
// fields for "open", "pending" and "solved" where the current
// status gets the value "1" and all others the value "0"
{$project: {
open: {
$cond: [ { $eq: [ "$Status", "open" ] }, 1, 0 ]
},
pending: {
$cond: [ { $eq: [ "$Status", "pending" ] }, 1, 0 ]
},
solved: {
$cond: [ { $eq: [ "$Status", "solved" ] }, 1, 0 ]
}
}},
// then create a new document by creating the sum of the created document
{$group: {
_id:1, // group all documents into one with the id "1"
open: { $sum: "$open" },
solved: { $sum: "$solved" },
pending: { $sum: "$pending" }
}},
]);
关于javascript - MongoDB 和 Node.js 性能中的查询与过滤器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29845049/