var oneWeekAgo = new Date();
oneWeekAgo.setDate(oneWeekAgo.getDate() - 7);
User.aggregate([
{ $match: { isAdmin: false, isActive: true } },
{
$group: {
_id: null,
totalCount: {
$sum: 1
}
}
},
])
User.aggregate([
{ $match: { isAdmin: false, dateCreated: { $gte: oneWeekAgo }, isActive: true } },
{
$group: {
_id: null,
lastWeekTotal: {
$sum: 1
}
}
},
])
有没有办法结合上面的 2 个聚合查询?
我想统计集合中的所有条目以及一周内创建的条目。 预期结果:
[ { _id: null, totalCount: 100 , lastWeekTotal: 10 } ]
最佳答案
你可以像这样将 $group
组合在一起,
- $cond运算符,一共有三个参数
($cond: [if check condition, then, else])
- 第一部分 if condition 使用 $and 运算符检查您的条件,如果条件为真则返回
1
否则返回0
User.aggregate([
{
$group: {
_id: null,
totalCount: {
$sum: {
$cond: [
{
$and: [
{ $eq: ["$isAdmin", false] },
{ $eq: ["$isActive", true] }
]
},
1,
0
]
}
},
lastWeekTotal: {
$sum: {
$cond: [
{
$and: [
{ $gte: ["$dateCreated", oneWeekAgo] },
{ $eq: ["$isAdmin", false] },
{ $eq: ["$isActive", true] }
]
},
1,
0
]
}
}
}
}
])
关于node.js - mongodb 匹配和组 2 查询合二为一,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63487510/