使用$的mongoose聚合存在于$ cond中
我想$project
如果一个字段存在,但不是它的价值,使用mongoose
model
aggregate
查询。 如果在$cond
使用$exists
可能会看起来像这样:
$project: { b: { $cond: { if : {$exists: ['$b', true]}, then : true, else : false } } }
但是,我必须在$cond
运算符中使用boolean
expression式。 在MongoDB shell中,我可以做类似的事情:
{$eq: ['$b', undefined]}
并产生预期的结果,但由于某种原因, mongoose
模型aggregate
,总是结果是true
。
例如,如果我有以下文件:
{ "a" : 1, "b" : 2 }, { "a" : 1 }
我需要以下结果:
{ "b": true }, { "b": false }
我怎么能用mongoose
这样做呢?
$exists
在MongoDB的 aggregate
查询中不受支持。 所以在aggregate
查询而不是$exists
可以使用$ifNull
。
句法:
{ $ifNull: [ <expression>, <replacement-expression-if-null> ] }
为更多
更新:
得到b
值为true
或false
可以尝试这个查询
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 } } } } ])