Hi, so I have an aggregation as such:
aggregate([
{ $match: { _id: "someID" } },
{ $unwind: "$array1" },
{
$project: {
_id: {
$cond: [{ $in: [someID, "$array1.array2._id"] }, "$array1._id", null]
},
another_field: {
$cond: [{ $in: [someID, "$array1.array2._id"] }, "$array1.other_field", null]
}
}
}
])
Is there any way to condense this such that the $cond clause only runs once? Or does Mongo optimize repeated conditions like this such that it is run once anyway?
Ideally if I can declare $cond to run only once, then use that result for the projection of various fields, that’ll be ideal. If I have multiple fields relying on this condition, it’s going to cause a lot of duplicate code where the only difference is what field I return as part of array1.
I understand that because the truth outcome is different for every field, $cond may not be declared once and reused. What about $in? Can that be run once and reused?