MongoDB条件聚合 [英] MongoDB conditional aggregation

查看:148
本文介绍了MongoDB条件聚合的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想对条件应用汇总。

假设a我有4个这样的文档:

Suppose a I have 4 documents like this :

{
    "_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
}

我希望聚合发送结果:

I would like the aggregation to send result :

1°)如果存在至少一个文档,

"Running" : true && "hasQuery" : true

然后根据条件(其他文档)进行过滤

"hasQuery" : false && "Running" : false &&  "Active" : true

2°) else(表示存在的文档具有)

"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

or:

"Active" : true,
"Running" : false,
"hasQuery" : true,
"RunningActiveRecordHasQuery" : false,
"AnyNotRunningActiveRecordHavingNoQuery" : false,
"AnyActiveRecordNotRunning" : true

现在,缺少条件过滤器。 ..
我还在搜索,找到后会发布答案!

Now Conditional filter is missing... I'm still searching and will post answer when found !

这篇关于MongoDB条件聚合的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆