Database
db={"products":[{_id:ObjectId("60d87d6fafd7a1377c03b2e6"),productName:"noodles instant",description:"lorem ipsum ... ... ...."},{_id:ObjectId("60d87d6fafd7a1377c03b2e7"),productName:"Sandal",description:"lorem ipsum ... ... ...."}],"transactions":[{_id:ObjectId("60d8781031308dbf565eaaa8"),trasactionSerial:"TRS20210000001",productInTransactions:[{_id:ObjectId("60d8781031308dbf565eaab9"),productId:ObjectId("60d87d6fafd7a1377c03b2e6"),qty:1500},{_id:ObjectId("60d8781031308dbf565eaa47"),productId:ObjectId("60d87d6fafd7a1377c03b2e7"),qty:200}]},{_id:ObjectId("60d8781031308dbf565eaab7"),trasactionSerial:"TRS20210000002",productInTransactions:[{_id:ObjectId("60d8781031308dbf565eaab9"),productId:ObjectId("60d87d6fafd7a1377c03b2e6"),qty:100},{_id:ObjectId("60d8781031308dbf565eaa47"),productId:ObjectId("60d87d6fafd7a1377c03b2e7"),qty:300}]}]}
Query
db.products.aggregate([{"$lookup":{"from":"transactions","let":{"pId":"$_id"},"pipeline":[{"$unwind":"$productInTransactions"},{"$match":{"$expr":{"$eq":["$productInTransactions.productId","$$pId"]},},},{"$group":{"_id":"$$pId","qtyInTransaction":{"$sum":"$productInTransactions.qty"}},},],"as":"matchedTransactions"}},{"$project":{"_id":1,"description":1,"qtyInTransaction":{"$arrayElemAt":["$matchedTransactions.qtyInTransaction",0]}},},])