gpt4 book ai didi

node.js - 对一个查询中具有多个条件的文档进行计数

转载 作者:太空宇宙 更新时间:2023-11-04 03:17:42 24 4
gpt4 key购买 nike

我正在尝试计算 mongoDB 中的数据库记录(使用 mongoose),其中记录的状态为待处理、已批准以及已拒绝。因此,我基本上试图获得一个可以显示每个计数并将其显示在我的 View 中的结果,即:

待处理:35批准:97拒绝:12

我有这个,但它只算“待处理”。有没有一种方法可以在一个查询中计算所有 3 个查询,或者我是否需要运行 3 个单独的查询并获取每个查询的结果?

Product.countDocuments({status: 'pending', userId: req.session.user._id})
.then(pending => {
if (!pending) {
return next();
}
req.pending = pending;
next();
})
.catch(err => {
console.log(err);
});

编辑:我已经设法在某种程度上做到了这一点,在控制台中我得到了所有结果的计数,但只需要弄清楚如何将每个结果放入它自己的变量中。

Product.aggregate([
{ $group: { _id: { status: "$status"}, totalStatus: {$sum: 1} } }
])
.then(function (res) {
console.log(res);
next();
});

最佳答案

要在单个查询中查找多个计数,请使用 mongodb 聚合框架,它可以在多个阶段操作数据,您的问题已经得到解答,请访问下面的链接。我为您更新查询。 Multiple Counts with single query in mongodb

Product.aggregate([
{ "$facet": {
"Pending": [
{ "$match" : { "status": { "$exists": true, "$in":["pending"] }}},
{ "$count": "Pending" },
],
"Approved": [
{ "$match" : {"status": { "$exists": true, "$in": ["approved"] }}},
{ "$count": "Approved" }
],
"Rejected": [
{ "$match" : {"status": { "$exists": true, "$in": ["rejected"] }}},
{ "$count": "Rejected" }
]
}},
{ "$project": {
"Pending": { "$arrayElemAt": ["$Pending.Pending", 0] },
"Approved": { "$arrayElemAt": ["$Approved.Approved", 0] },
"Rejected": { "$arrayElemAt": ["$Rejected.Rejected", 0] }
}}
])

关于node.js - 对一个查询中具有多个条件的文档进行计数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54097568/

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