How can I use the MongoDB aggregation pipeline to calculate totals from deeply nested sub-documents while filtering the main documents

0 votes

How can I use the MongoDB aggregation pipeline to calculate totals from deeply nested sub-documents while filtering the main documents?

I have a collection with deeply nested sub-documents, and I need to calculate totals (e.g., sum or count) from these nested fields using the MongoDB aggregation pipeline. At the same time, I want to filter the main documents based on specific criteria. How can I achieve this efficiently?

Nov 19 in Web Development by Nidhi
• 4,940 points
114 views

1 answer to this question.

0 votes

In MongoDB, you can use the aggregation pipeline to calculate totals from deeply nested sub-documents while filtering the main documents. Here's how you can achieve this:

Match Stage: Use the $match stage to filter the main documents based on your criteria.

Unwind Stage: Use $unwind to deconstruct arrays within your documents. This is useful if your nested sub-documents are within arrays.

Project Stage: Use $project to shape your documents, focusing on the fields necessary for your calculations, including the nested sub-document fields.

Group Stage: Use $group to aggregate the necessary fields and calculate totals.

Here's a basic example. Suppose you have a orders collection where each order document contains an array of items, and you want to calculate the total quantity ordered for each productId:

[

  {

    "_id": 1,

    "customer": "John Doe",

    "items": [

      { "productId": "A", "quantity": 2 },

      { "productId": "B", "quantity": 1 }

    ]

  },

  {

    "_id": 2,

    "customer": "Jane Doe",

    "items": [

      { "productId": "A", "quantity": 1 },

      { "productId": "C", "quantity": 5 }

    ]

  }

]

To calculate the total quantity for each productId, follow the steps:


db.orders.aggregate([

  {

    // Filter main documents as needed

    $match: { "customer": { $exists: true } }

  },

  {

    // Deconstruct items array

    $unwind: "$items"

  },

  {

    // Prepare necessary fields

    $project: {

      productId: "$items.productId",

      quantity: "$items.quantity"

    }

  },

  {

    // Group by productId to calculate total quantities

    $group: {

      _id: "$productId",

      totalQuantity: { $sum: "$quantity" }

    }

  }

])

This pipeline does the following:

Filters documents based on whether the customer field exists ($match).

Unwinds the items array to work with each item independently.

Projects the fields necessary for calculation, extracting productId and quantity.

Groups the documents by productId while summing the quantity field to calculate the total quantity for each product.

answered Nov 19 by kavya

Related Questions In Web Development

0 votes
0 answers

How to calculate total number of documents in MongoDB?

How to calculate total number of documents ...READ MORE

Nov 13 in Web Development by Nidhi
• 4,940 points
48 views
0 votes
0 answers
+1 vote
1 answer

How to access the Angularjs scope of a particular html element from our console?

Hello, You should follow the below steps:-- 1.Compile and ...READ MORE

answered Jan 21, 2020 in Web Development by Niroj
• 82,840 points

edited Jan 21, 2020 by Niroj 3,041 views
0 votes
1 answer

Hadoop MapReduce vs MongoDB MapReduce

Hadoop vs MongoDB MR: 1) Hadoop's MR can ...READ MORE

answered Mar 26, 2018 in Big Data Hadoop by nitinrawat895
• 11,380 points
1,432 views
0 votes
1 answer

How can we send data from MongoDB to Hadoop?

The MongoDB Connector for Hadoop reads data ...READ MORE

answered Mar 27, 2018 in Big Data Hadoop by nitinrawat895
• 11,380 points
2,129 views
0 votes
0 answers

How can I add a connection between Mongodb and Tableau

What I want? Parse the XML to JSON ...READ MORE

May 18, 2018 in Tableau by ghost
• 1,790 points
794 views
0 votes
2 answers

How do I integrate Kdb+ and hadoop?

 kdb+ could be installed on every Hadoop ...READ MORE

answered Aug 6, 2018 in Big Data Hadoop by Abhi
• 3,720 points
1,768 views
0 votes
1 answer
0 votes
1 answer

How to calculate total number of documents in MongoDB?

You can use countDocuments() method. Definition: The countDocuments() method ...READ MORE

answered Dec 6 in Web Development by Navya
46 views
webinar REGISTER FOR FREE WEBINAR X
REGISTER NOW
webinar_success Thank you for registering Join Edureka Meetup community for 100+ Free Webinars each month JOIN MEETUP GROUP