Database
db={users:[{"_id":"user1"},{"_id":"user2"},{"_id":"user3"}],orders:[{"orderid":"1111","order_type":"individual","users":[{"name":"user1","phone":982928,"items":[{"name":"AAA","qty":20,"price":10},{"name":"BBB","qty":30,"price":15}]},{"name":"user2","phone":948783,"items":[{"name":"AAA","qty":10,"price":10},{"name":"CCC","qty":5,"price":20}]},{"name":"user3","phone":787868,"items":[{"name":"BBB","qty":40,"price":10},{"name":"CCC","qty":15,"price":20}]}]},{"orderid":"2222","order_type":"bulk","users":[{"name":"user1","phone":982928},{"name":"user3","phone":787868}],"items":[{"name":"AAA","qty":3,"price":10},{"name":"BBB","qty":15,"price":10},{"name":"only_in_bulk","qty":15,"price":10}]}],meta:[{"by":"steevej","at":"gmail","dot":"com"}]}
Query
db.users.aggregate([{"$project":{_id:1}},{"$lookup":{"from":"orders","localField":"_id","foreignField":"users.name","let":{user_name:"$_id"},"as":"_tmp_lookup_orders","pipeline":[{"$set":{"_tmp_unified_items":{"$cond":{"if":{$eq:["$order_type","bulk"]},"then":"$items","else":{"$reduce":{"input":"$users","initialValue":null,"in":{$cond:{"if":["$$user_name","$$this.name"],"then":"$$this.items","else":"$$value"}}}}}}}},{$set:{"_tmp_mapped_unified_items":{"$map":{"input":"$_tmp_unified_items","in":"$$this.name"}}}}]}},{"$set":{"orders":{"$map":{"input":"$_tmp_lookup_orders","as":"order","in":"$$order.orderid"}},"items":{$reduce:{"input":"$_tmp_lookup_orders","initialValue":[],"in":{"$setUnion":["$$value","$$this._tmp_mapped_unified_items"]}}}}},{$unset:"_tmp_lookup_orders"}])