• python
  • javascript
  • reactjs
  • sql
  • c#
  • java
Facebook Twitter Instagram
Devs Fixed
  • python
  • javascript
  • reactjs
  • sql
  • c#
  • java
Devs Fixed
Home ยป Resolved: MongoDB – Aggregate a sales table from orders

Resolved: MongoDB – Aggregate a sales table from orders

0
By Isaac Tonny on 18/06/2022 Issue
Share
Facebook Twitter LinkedIn

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:

  1. $unwind – Deconstruct products array to multiple documents.
  2. $group – Group by products.produtId and sum for products.quantity and products.total.
  3. $project – Decorate output documents.

Sample Mongo Playground

If you have better answer, please add a comment about this, thank you!

aggregation-framework mongodb mongodb-query mongoose
Share. Facebook Twitter LinkedIn

Related Posts

Resolved: Using AWK to count multiple patterns in a file

01/04/2023

Resolved: significance letter above bar graphic in wrong order

01/04/2023

Resolved: VBA – Applying border around the areas with value/text

01/04/2023

Leave A Reply

© 2023 DEVSFIX.COM

Type above and press Enter to search. Press Esc to cancel.