【发布时间】: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