node.js - mongodb匹配和组2查询合二为一
问题描述
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 条件使用 $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
]
}
}
}
}
])
推荐阅读
- python - 保留重复值 - python 字典
- vue.js - 如何在单击按钮vue js上反转消息
- scala - Spark Scala - 将带有毫秒的时间戳转换为没有毫秒的时间戳
- r - R中数据表中的缺失值
- streaming - Vega Vega-lite 流媒体
- dax - 用于保存按日期分组的最大值的 Dax 计算列
- java - 没有可用的“javax.sql.DataSource”类型的合格 bean:在候选中找到多个“主要”bean:
- heroku - Heroku 应用程序错误 - 代码=H10 desc="应用程序崩溃"
- javascript - 如果元素被溢出完全隐藏,设置可见性是否多余?
- vhdl - 高密度脂蛋白; 如何在受约束的数组中约束不受约束的 std_logic_vector