mongoose aggregate using $exists in $cond
You could use two $project
statement for this case and make use of the $ifNull operator (Just wont work when some_field
is set as false
in which case you can change the inner false
to something more suitable)
[
{
$project: {
test: {
$ifNull: [
'$some_field',
false
]
}
}
},
{
$project: {
test: {
$cond: {
if : {$eq: ['$test', false]},
then : false,
else : true
}
}
}
}
])
$exists
not supported in aggregate
query of MongoDB. So in aggregate
query instead of $exists
can use $ifNull
.
syntax:
{ $ifNull: [ <expression>, <replacement-expression-if-null> ] }
for more
Updated:
to get b
value as true
or false
can try this query
db.test.aggregate([
{
$project: {
b: {
$cond: [
{$ifNull: ['$b', false]}, // if
true, // then
false // else
]
}
}
}
])
Explanation:
b = $cond: [ 'if condition satisfied', 'then true', 'else false' ];
where condition = {$ifNull: ['$b', false]}
Here if $b
not exist then condition = false
otherwise condition = true
.
so if condition = true
then return then result that means b = true
if condition = false
then return else result means b = false