Database
db={"orders":[{"_id":"1","customer_id":"1","items":[{"product_id":"1","quantity":2},{"product_id":"2","quantity":5}]}],"product":[{"product_id":"1","name":"apple","price":2,"quantity":1,"free":0},{"product_id":"2","name":"banana","price":1,"quantity":3,"free":1}]}
Query
db.orders.aggregate([{"$match":{_id:"1"}},{"$unwind":"$items"},{"$lookup":{"from":"product","localField":"items.product_id","foreignField":"product_id","as":"product_docs"}},{"$set":{"product_doc":{"$first":"$product_docs"}}},{"$project":{"total_each":{"$multiply":[{$subtract:["$items.quantity",{"$multiply":[{$floor:{$divide:["$items.quantity","$product_doc.quantity"]}},"$product_doc.free"]}]},"$product_doc.price"]}}},{"$group":{"_id":"$_id","total":{"$sum":"$total_each"}}}])