Conditional $lookup

One idea that comes to mind is that you could use $facet.

One will start with

$match : { "fruit_name" : { "$exists" : 1 } }

and do the $lookup while the other will start with

$match : { "fruit_name" : { "$exists" : 0 } }

The issue I see is that each facet is limited to 16Gb which may or may not be an issue.

The other thing you could try is do 2 aggregations in a transaction. But I am not sure it is possible to do aggregations inside transactions.

Why 2 normal aggregations do not work?

Have you looked at the new $lookup variants with which you can have conditions and sub-pipeline?

1 Like