Here is an updated playground that improves from the previous one to do

There is a new $set in the lookup pipeline that $map(s) the unified items to only keep the item’s names. This is the $reduce mentioned in

The final $set of main pipeline then uses $setUnion to produces an array of unique items.

I left out the counting of unique_items because I prefer to get the list of unique items rather than just the count. The application layer can easily do the calculation. Obviously, the calculation could be done on the server to reduce bandwidth utilization but increase the CPU utilization.

I also left out the cleaning of the temporary results (all prefixed with tmp) like _tmp_lookup_orders. It makes understanding the different steps easier by keeping them.

1 Like