使用$存在$ redact与mongo聚合?

时间:2015-11-10 05:04:32

标签: mongodb mongoose mongodb-query aggregation-framework

我正在使用$ redact运算符:

{ $redact: {
    $cond: {
        "if": {
            "$lt": [ "$number1", "$number2" ],
        },
        "then": "$$KEEP",
        "else": "$$PRUNE"
    }
}}

我想$and: [{$lt:["$number1, $number2"]}, {$exists:[$number3, 1]}],但我无法获取$ exists,或检查null。

1 个答案:

答案 0 :(得分:1)

你想要$ifNull,因为它是一种""""等效的,具有在字段不存在的情况下返回备用值的附加功能:

{ "$redact": {
    "$cond": {
        "if": {
            "$and": [
               { "$lt": [ "$number1", "$number2" ] },
               { "$ifNull": [ "$number3", false ] }
            ]
        },
        "then": "$$KEEP",
        "else": "$$PRUNE"
    }
}}

因此,如果该字段存在,则返回该字段的值,这与说true基本相同(除非它的值实际上是false,在这种情况下,用{{换行1}}),或返回已作为$cond提供的备用。

相关问题