node.js - Single aggregation query for multiple groups -


my collection json

[    {       "_id" : 0,         "finalamount":40,       "payment":[          {             "_id":0,             "cash":20          },          {             "_id":1,             "card":20          }       ]    },    {       "_id" : 1,       "finalamount":80,       "payment":[          {             "_id":0,             "cash":60          },          {             "_id":1,             "card":20          }       ]    },    {       "_id" : 2,       "finalamount":80,       "payment":[          {             "_id":0,             "cash":80          }       ]    } ] 

i want have amount, cash , card group wise using aggregation framework. can help?

please consider _id objectid demo purpose have given 0 , 1. using node js , mongodb , want expected output in 1 query follows:

expected output:

{    "cash":160,    "card":40,    "total":200,    "count":3 } 

you try running following aggregation pipeline, although there might performance penalty or potential aggregation pipeline limits huge datasets since initial pipeline tries group documents in collection total document count , amount pushing documents temporary list, may affect performance down pipeline.

nonetheless, following solution yield given desired output given sample:

collection.aggregate([     {         "$group": {             "_id": null,             "count": { "$sum": 1 },             "doc": { "$push": "$$root" },             "total": { "$sum": "$finalamount" }         }     },     { "$unwind": "$doc" },     { "$unwind": "$doc.payment" },     {         "$group": {             "_id": null,             "count": { "$first": "$count" },             "total": { "$first": "$total" },                         "cash": { "$sum": "$doc.payment.cash" },             "card": { "$sum": "$doc.payment.card" }         }     } ], function(err, result) {     console.log(result); }); 

Comments

Popular posts from this blog

asynchronous - C# WinSCP .NET assembly: How to upload multiple files asynchronously -

aws api gateway - SerializationException in posting new Records via Dynamodb Proxy Service in API -

asp.net - Problems sending emails from forum -