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//每个“priceAmt”的总和
最佳答案
您必须使用 $unwind
运算符将数组项转换为单个文档。
db.test3.aggregate({$unwind: "$results"}, {$unwind: "$results.result.cost"}, {$group : {_id: "", total : {$sum: "$results.result.cost.priceAmt"}}}, {$project: {_id: 0, total: 1}})
$unwind
需要应用两次,因为您有一个嵌套数组。
关于mongodb - 求和 Mongo 子文档数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19664748/