在$ cond中使用$ exists合并的猫鼬

Tom*_*omG 5 mongoose mongodb node.js

我想$project使用mongoose model aggregate查询来确定是否存在一个字段,但不是它的值。如果可以使用$existsin $cond,它将看起来像这样:

$project: {
    b: {
        $cond: {
            if    : {$exists: ['$b', true]},
            then  : true,
            else  : false
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

但是,我必须boolean$cond运算符中使用表达式。在MongoDB Shell中,我可以执行以下操作:

{$eq: ['$b', undefined]}
Run Code Online (Sandbox Code Playgroud)

会产生预期的结果,但由于mongoose模型aggregate的原因,它始终会产生true

例如,如果我有以下文件:

{
    "a" : 1,
    "b" : 2
},
{
    "a" : 1
}
Run Code Online (Sandbox Code Playgroud)

我需要以下结果:

{
    "b": true
},
{
    "b": false
}
Run Code Online (Sandbox Code Playgroud)

我该如何做mongoose呢?

Sha*_*Roy 9

$existsaggregate查询MongoDB不支持。因此在aggregate查询中代替$exists可以使用$ifNull

句法:

{ $ifNull: [ <expression>, <replacement-expression-if-null> ] }
Run Code Online (Sandbox Code Playgroud)

更多

更新:

获得b价值truefalse可以尝试此查询

db.test.aggregate([
    {
        $project: {
            b: { 
                $cond: [
                    {$ifNull: ['$b', false]}, // if
                    true, // then
                    false // else
                ]
            }
        }
    }
])
Run Code Online (Sandbox Code Playgroud)

说明:

b = $cond: [ 'if condition satisfied', 'then true', 'else false' ];
Run Code Online (Sandbox Code Playgroud)

其中,condition = {$ifNull: ['$b', false]} 在这里,如果$b不存在,那么condition = false,否则condition = true

所以如果condition = true然后返回则结果意味着b = true
如果condition = false然后返回否则结果意味着b = false