json - Mongodb $sum with Subarray list item values -


i trying calculate total number of products in order in sub-array.

facing trouble $sum while trying calculate.

my attempt

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

my result

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

while trying sum below

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

i getting 0 result. please see below result.

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

please find best solution issue.

your agreggation correct, problem qty field string. try changing "qty":3. should work


Comments