Conditional $lookup

It is definitely an ‘alternative’, but has many drawbacks.

For example, { $match: { fruit_name: { $ne: null }}}, is going to be nonperformant even with an index, especially when “fruit_name” has many different values.

I would say, GENERALLY speaking, doing

db.child_fruit.aggregate([
  {$lookup: {
    from: ‘fruit’,
    …
  }}
]);

is going to be more performant than your unionWith example. Obviously depends on a bunch of factors (collection sizes, index values, etc.). The originally proposed solution by Asya is still the best (using some alternative operator to “fake” a lookup that will cancel out the possibility of a null lookup).

It would be awesome if the $lookup operator just supported some sort of skip field based on a conditional

$lookup: {
  ...,
  skip: <condition>
}
2 Likes