Condensing this aggregation such that $cond/$in only runs once

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?

You can add one $addFields extra stage after the unwind to hold that value.
And use that value in the project condtion.

{"$addFields"  {"myTempField" { $in: [someID, "$array1.array2._id"] }}}

After project it will go anyways

1 Like

This topic was automatically closed 5 days after the last reply. New replies are no longer allowed.