Q:

Query to group distinct values and show sum of array values in mongodb

I wanted to group by cart.name and find the sum of cart.qty in mongodb. Below is sample document
{
    "_id" : ObjectId("581323379ae5e607645cb485"),
    "cust" : {
            "name" : "Customer 1",
            "dob" : "09/04/1989",
            "mob" : 999999999,
            "loc" : "Karimangalam",
            "aadhar" : {

            }
    },
    "cart" : [
            {
                    "name" : "Casual Shirt",
                    "qty" : 1,
                    "mrp" : 585,
                    "discperc" : 10,
                    "fit" : null,
                    "size" : "L"
            },
            {
                    "name" : "Casual Shirt",
                    "qty" : 1,
                    "mrp" : 500,
                    "discperc" : 0,
                    "fit" : null,
                    "size" : "L"
            },
            {
                    "name" : "Cotton Pant",
                    "qty" : 1,
                    "mrp" : 850,
                    "discperc" : 0,
                    "fit" : null,
                    "size" : "34"
            },
            {
                    "name" : "Cotton Pant",
                    "qty" : 1,
                    "mrp" : 1051,
                    "discperc" : 10,
                    "fit" : null,
                    "size" : "34"
            }
    ],
    "summary" : {
            "bill" : 2822.4,
            "qty" : 4,
            "mrp" : 2986,
            "received" : "2800",
            "balance" : -22.40000000000009
    },
    "createdAt" : ISODate("2016-10-28T10:06:47.367Z"),
    "updatedAt" : ISODate("2016-10-28T10:06:47.367Z")
}

There are many document like this. I want the output as below distinct product name (cart.name) and its total qty
{Casual Shirt , 30},
{Cotton Pant , 10},
{T-Shirt , 15},
{Lower , 12}

Here is my query trying to group by cart.name and sum qty
db.order.aggregate( [    
{ $unwind: "$cart" },    
{ $group: {  
    _id: "$cart.name",
    totalQTY: { $sum:"$cart.qty"},
        count: { $sum: 1 }
    }    
} 
] )

but it displays wrong totalQty values for each product name. I checked manually.
Please give me the correct query.

A:

> db.collection.aggregate([
...     { $unwind: "$cart" },
...     { $group: { "_id": "$cart.name", totalQTY: { $sum: "$cart.qty" }, count: { $sum: 1 } } }
... ])

I get the following result:  
{ "_id" : "Cotton Pant", "totalQTY" : 2, "count" : 2 }
{ "_id" : "Casual Shirt", "totalQTY" : 11, "count" : 2 }

I'm not sure what you're looking for, it looks like your aggregation pipeline is correct.  (Note I changed the Casual Shirt Quantity to be 10 and 1 respectively)

