MongoDB条件聚合
我想将聚合应用于条件 假设我有4个这样的文档:MongoDB条件聚合,mongodb,conditional,Mongodb,Conditional,我想将聚合应用于条件 假设我有4个这样的文档: { "_id" : 1, "Action" : "Bufferize", "Active" : true, "Running" : true, "hasQuery" : true } { "_id" : 2, "Action" : "Numerize", "Active" : true, "Running" : false, "hasQuery" : false }
{
"_id" : 1,
"Action" : "Bufferize",
"Active" : true,
"Running" : true,
"hasQuery" : true
}
{
"_id" : 2,
"Action" : "Numerize",
"Active" : true,
"Running" : false,
"hasQuery" : false
}
{
"_id" : 3,
"Action" : "Resize",
"Active" : false,
"Running" : true,
"hasQuery" : true
}
{
"_id" : 4,
"Action" : "Colorize",
"Active" : true,
"Running" : true,
"hasQuery" : false
}
我希望聚合发送结果:
1°)如果存在至少一个具有
"Running" : true && "hasQuery" : true
"Running" : true && "hasQuery" false
|| "Running" : false && "hasQuery" true
|| "Running" : false && "hasQuery" false
然后筛选条件(其他文档):
"hasQuery" : false && "Running" : false && "Active" : true
2°)else(如果存在文档,则使用方法)
"Running" : true && "hasQuery" : true
"Running" : true && "hasQuery" false
|| "Running" : false && "hasQuery" true
|| "Running" : false && "hasQuery" false
然后根据标准进行筛选
"Running" : false && "Active" : true
如何执行此聚合?我有一个第一种方法:
db.test_col.aggregate(
{
$project:
{
_id: 1,
Running : 1,
Active : 1,
hasQuery : 1,
Action : 1,
RunningActiveRecordHasQuery:
{
$cond: { if: { $and: [ "$Running", "$hasQuery", "$Active"] }, then: true, else: false }
},
AnyNotRunningActiveRecordHavingNoQuery:
{
$cond: { if: { $and: [ {$eq: [ "$Running", false ] }, {$eq : [ "$hasQuery", false]}, "$Active"] }, then: true, else: false }
},
AnyActiveRecordNotRunning:
{
$cond: { if: { $and: [ {$eq: [ "$Running", false ] }, "$Active"] }, then: true, else: false }
}
}
}
)
它打印的示例如下:
"Active" : true,
"Running" : true,
"hasQuery" : true,
"RunningActiveRecordHasQuery" : true,
"AnyNotRunningActiveRecordHavingNoQuery" : false,
"AnyActiveRecordNotRunning" : false
或:
现在缺少条件筛选器。。。
我仍在搜索,找到答案后会发布 谢谢JohnnyHK的更正。问题在这里解决了。问题在这里解决了: