2

I have a collection with the following data:

{
    "_id": "1",
    "arrlstdetails": [{
        "_id": "1",
        "quantity": 35.5,
        "units": "m3"
    }]
},{
    "_id": "2",
    "arrlstdetails": [{
            "_id": "1",
            "quantity": 35.5,
            "units": "m3"
        },
        {
            "_id": "2",
            "quantity": 12.25,
            "units": "m3"
        },
        {
            "_id": "3",
            "quantity": 28.20,
            "units": "t"
        }
    ]
}

I would like to perform the MongoDB Aggregation for a sum of quantity filtering by unit(m3 or t).

And this is the result that I would like to get after the querying:

Example: 1.

{
"Unit":"m3",
"Total quantity sum":"83.25"
}

Example: 2.

{
"Unit":"t",
"Total quantity sum":"28.20"
}

How can I query to get the sum of quantity?

Harshal Yelpale
  • 535
  • 3
  • 21
  • You should refer at least MongoDB document and try to put your code whatever you have tried. Though please check the answer. – Hardik Shah Nov 23 '18 at 13:29

1 Answers1

6

Use $unwind and $group

db.getCollection('test').aggregate([
    { $unwind: "$arrlstdetails" },
    { $group : {
        _id : "$arrlstdetails.units",
        "Total quantity sum" : {$sum : "$arrlstdetails.quantity"}
    }}
])
Hardik Shah
  • 4,042
  • 2
  • 20
  • 41