【问题标题】:Query to group distinct values and show sum of array values in mongodb查询以对不同的值进行分组并在 mongodb 中显示数组值的总和
【发布时间】:2016-11-03 13:40:53
【问题描述】:

我想按 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 值。我手动检查了。

请给我正确的查询。

【问题讨论】:

    标签: mongodb sum aggregation-framework


    【解决方案1】:
    > 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)

    【讨论】:

    • 谢谢。它工作正常。我使用 $match 计算总数,并按 $cart 而不是 $cart.name 分组。错误查询 db.collection.aggregate([ { $unwind: "$cart" }, { $match: { 'cart.name' : "Casual Shirt" } } - 匹配产品名称 { $group: { "_id": "$cart", totalQTY: { $sum: "$cart.qty" }, count: { $sum: 1 } } } ... ])
    猜你喜欢
    • 2021-01-23
    • 2015-06-24
    • 1970-01-01
    • 2016-12-06
    • 2017-09-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-02-23
    相关资源
    最近更新 更多