How to check if sub-field exists and is not null in mongodb aggregation?
Wrapping $ifNull
in $cond
does the trick, even with the subfield problem.
pipelineStages.push({
$addFields: {
newField: {
$cond: [
{
"$ifNull": [
"$otherField.subField",
false
]
},
"$otherField.subField",
1
]
}
}
);
Did you try this version of condition:
pipelineStages.push({ $addFields:
{field:
{$cond: [{$and: [{"$otherField": {"$exists": true}}, {"$otherField.subField": {"$exists": true}}]}, "$otherField.subField", 1]
}
}
});
To check if the field exists and is not null, use:
pipelineStages.push({
$addFields: {
field: {
$cond: [
{"$gt": [$otherField, null]}, "$otherField.subField", 1
]
}
}
})
On the contrary, to check if the field doesn't exist or is null, use:
{"$lte": [$otherField, null]}