【问题标题】:Mongodb $sum with Subarray list item valuesMongodb $sum 与子数组列表项值
【发布时间】:2016-07-21 20:39:04
【问题描述】:

我正在尝试计算我的订单中实际位于子数组中的产品总数。

在尝试计算时遇到 $sum 问题。

我的尝试

db.getCollection('orders').aggregate([
{$match:{'order_no':'GHT19'}},
{$unwind:"$products_list"}
])

我的结果

{
    "_id" : ObjectId("57838a3a3628f76b52511ffe"),
    "order_no" : "GHT19",
    "origin_port" : "Vizag Port",
    "destination_port" : "Hankou Port"
    "products_list" : {
        "box_no" : "1",
        "product_name" : "Mobile",
        "qty" : "5"
    }
}


{
    "_id" : ObjectId("57838a3a3628f76b52511ffe"),
    "order_no" : "GHT19",
    "origin_port" : "Vizag Port",
    "destination_port" : "Hankou Port"
    "products_list" : {
        "box_no" : "2",
        "product_name" : "Television",
        "qty" : "2"
    }
}


{
    "_id" : ObjectId("57838a3a3628f76b52511ffe"),
    "order_no" : "GHT19",
    "origin_port" : "Vizag Port",
    "destination_port" : "Hankou Port",
    "products_list" : {
        "box_no" : "3",
        "product_name" : "Radio",
        "qty" : "2"
    }

}

在尝试像下面这样进行 SUM 时

db.getCollection('orders').aggregate([
{$match:{'order_no':'GHT19'}},
{$unwind:"$products_list"},
{$group: {
    _id: '$products_list.box_no', 
    "total_products": {$sum: "$products_list.qty" }
  }
}
])

我得到零结果。请看下面的结果。

{
    "_id" : "2",
    "total_products" : 0
}


{
    "_id" : "3",
    "total_products" : 0
}


{
    "_id" : "1",
    "total_products" : 0
}

请为我的问题找到最佳解决方案。

【问题讨论】:

    标签: json node.js mongodb mongodb-query


    【解决方案1】:

    您的聚合是正确的,问题是 qty 字段是一个字符串。尝试将其更改为“数量”:3。应该可以的

    【讨论】:

    • 感谢您的建议有效。我什至更改了 $group 中的 "_id" : 1 。最后,我得到了结果:)
    【解决方案2】:

    您只能使用数值计算$sumhttps://docs.mongodb.com/manual/reference/operator/aggregation/sum/

    您可以使用以下命令将所有 products_list.qty 转换为数字:

    db.device.find().forEach(function(data) {
    
        data.products_list.forEach(function(data2) {
    
            db.device.update({
                "_id": data._id,
                "products_list.box_no": data2.box_no
            }, {
                "$set": {
                    "products_list.$.qty": parseInt(data2.qty)
                }
            });
    
        });
    })
    

    然后执行你的聚合

    【讨论】:

      猜你喜欢
      • 2018-03-25
      • 2020-06-07
      • 2019-04-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-05-22
      • 1970-01-01
      相关资源
      最近更新 更多