I got quite an annoying problem, and I can't seem to find any solution for my specific case. In my mongo agggregation pipeline, I'd like to add a field, and depending on the existence of another field's subfield, I'd like to assign the value of that other field's subfield, or 1 if that other field's subfield does not exist.
Here is what I tried:
pipelineStages.push(
{$addFields:
{field:
{$cond: [
{$ne: ["$otherField.subField", null]},
"$otherField.subField", 1]
}
}
}
);
However, it only works fine for the case that the field exists. In the other, that new field is not added to the pipeline at all. Any ideas what I'm doing wrong?
Wrapping $ifNull
in $cond
does the trick, even with the subfield problem.
pipelineStages.push({
$addFields: {
newField: {
$cond: [
{
"$ifNull": [
"$otherField.subField",
false
]
},
"$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]}
Did you try this version of condition:
pipelineStages.push({ $addFields:
{field:
{$cond: [{$and: [{"$otherField": {"$exists": true}}, {"$otherField.subField": {"$exists": true}}]}, "$otherField.subField", 1]
}
}
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With