Database

db={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.orders.aggregate([{$unwind:"$users"},{$project:{orderid:1,user:"$users.name",items:{$ifNull:["$users.items",[]]}/** Ensuring 'items' field is included, even if empty*/}},{$group:{_id:"$user",orders:{$addToSet:"$orderid"},/** Collect unique order ids*/unique_items:{$addToSet:{$map:{input:{$ifNull:["$items",[]]},/** Handle missing 'items' array*/as:"item",in:"$$item.name"}}}}},{$project:{user:"$_id",orders:1,unique_items:1,unique_items_count:{$size:"$unique_items"}/** Count unique items*/}}])

Result