3
 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"

4

1 回答 1

4

您必须使用$unwind运算符将​​数组项转换为单个文档。

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

$unwind需要应用两次,因为您有一个嵌套数组。

于 2013-10-29T17:27:22.573 回答