查询以对不同的值进行分组并在mongodb中显示数组值的总和

时间:2016-11-03 13:40:53

标签: mongodb sum aggregation-framework

我想通过cart.name进行分组,并在mongodb中找到cart.qty的总和。以下是示例文档

{
    "_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")
}

有很多这样的文件。我希望输出如下面的不同产品名称(cart.name)及其总数量

{Casual Shirt , 30},
{Cotton Pant , 10},
{T-Shirt , 15},
{Lower , 12}

这是我的查询尝试按cart.name和sum qty

进行分组
db.order.aggregate( [    
{ $unwind: "$cart" },    
{ $group: {  
    _id: "$cart.name",
    totalQTY: { $sum:"$cart.qty"},
        count: { $sum: 1 }
    }    
} 
] )

但它为每个产品名称显示错误的totalQty值。我手动检查了。

请给我正确的查询。

1 个答案:

答案 0 :(得分:0)

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

我得到以下结果:

{ "_id" : "Cotton Pant", "totalQTY" : 2, "count" : 2 }
{ "_id" : "Casual Shirt", "totalQTY" : 11, "count" : 2 }

我不确定您在寻找什么,看起来您的聚合管道是正确的。 (注意我将休闲衬衫数量分别改为10和1)