求和Mongo子文档数组

时间:2013-10-29 17:05:51

标签: mongodb

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

我尝试了以下不成功:

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

修改

期望的输出:

100 // sum of each "priceAmt"

1 个答案:

答案 0 :(得分: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需要应用两次,因为你有一个嵌套数组。

相关问题