Question:
Assuming there is a collection where each document contains an array of objects called products.
//Document 1
//Document 2
//Document 3
Now each document contains an array of products sold, for example product with the id “62aac8cfb5722d4c628a4a24” appears in multiple orders. what I want to do is use aggregate to return an array of objects called sales. each object in the array has the product Id (unique), sum of quantity from all documents and sum of total from all documents.
Answer:
$unwind
– Deconstruct products
array to multiple documents.
$group
– Group by products.produtId
and sum for products.quantity
and products.total
.
$project
– Decorate output documents.
Sample Mongo Playground
If you have better answer, please add a comment about this, thank you!