Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Summing Mongo Sub-Document Array

Tags:

mongodb

 db.test3.find() 
{ "_id" : 1, "results" : [{"result" : {"cost" : [ { "priceAmt" : 100 } ] } } ] }

I tried the following unsucessfully:

db.test3.aggregate({$group : {_id: "", total : {$sum: 
$results.result.cost.priceAmt"}}}, {$project: {_id: 0, total: 1}})
{ "result" : [ { "total" : 0 } ], "ok" : 1 }

EDIT

Desired output:

100 // sum of each "priceAmt"

like image 598
Kevin Meredith Avatar asked Dec 04 '25 13:12

Kevin Meredith


1 Answers

You'll have to use the $unwind operator to turn array items into individual documents.

db.test3.aggregate({$unwind: "$results"}, {$unwind: "$results.result.cost"}, {$group : {_id: "", total : {$sum: "$results.result.cost.priceAmt"}}}, {$project: {_id: 0, total: 1}})

The $unwind needs to be applied twice because you have a nested array.

like image 140
Rafa Avatar answered Dec 07 '25 09:12

Rafa



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!