使用$的mongoose聚合存在于$ cond中

我想$project如果一个字段存在,但不是它的价值,使用mongoose model aggregate查询。 如果在$cond使用$exists可能会看起来像这样:

 $project: { b: { $cond: { if : {$exists: ['$b', true]}, then : true, else : false } } } 

但是,我必须在$cond运算符中使用booleanexpression式。 在MongoDB shell中,我可以做类似的事情:

 {$eq: ['$b', undefined]} 

并产生预期的结果,但由于某种原因, mongoose模型aggregate ,总是结果是true

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

 { "a" : 1, "b" : 2 }, { "a" : 1 } 

我需要以下结果:

 { "b": true }, { "b": false } 

我怎么能用mongoose这样做呢?

$existsMongoDB的 aggregate查询中不受支持。 所以在aggregate查询而不是$exists可以使用$ifNull

句法:

 { $ifNull: [ <expression>, <replacement-expression-if-null> ] } 

为更多

更新:

得到b值为truefalse可以尝试这个查询

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

你可以使用两个$project语句来处理这种情况,并使用$ ifNull操作符(当some_field被设置为false ,将不会工作,在这种情况下,您可以将内部的false更改为更适合的东西)

 [ { $project: { test: { $ifNull: [ '$some_field', false ] } } }, { $project: { test: { $cond: { if : {$eq: ['$test', false]}, then : false, else : true } } } } ])