汇总Mongo子文档数组

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

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 需要应用两次,因为你有一个嵌套数组。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接