我想运行多个查询来获取MongoDB集合的计数。就像,我想运行一个查询来查找待定状态用户和已完成状态用户。像这样的东西,有没有办法在查询/聚合中编写这两个条件并在MongoDB中获得单独的结果?
我的要求是,
我需要获取状态待定,已完成并在今天,昨天,上周和上个月开启的用户数。
我需要这样的不同状态,
{
"today": {
"pending": 10,
"completed": 13,
"open": 5
},
"yesterday": {
"pending": 10,
"completed": 13,
"open": 5
},
"lastWeek": {
"pending": 10,
"completed": 13,
"open": 5
},
"lastMonth": {
"pending": 10,
"completed": 13,
"open": 5
}
}
答案 0 :(得分:1)
您可以使用聚合$group
阶段:
db.Collection.aggregate([
{$project: {
// If your pending/completed field is set to 1 or true
pending: {$cond: [{$eq: ["$pending", 1 /* or true */]}, 1, 0]},
completed: {$cond: [{$eq: ["$completed", 1 /* or true */]}, 1, 0]}
}},
{$group: {
_id: //what you want,
pending: {$sum: "$pending"},
completed: {$sum: "$completed"}
}}
]);