汇总Mongo子文档数组 [英] Summing Mongo Sub-Document Array

查看:81
本文介绍了汇总Mongo子文档数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

 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 }

编辑

所需的输出:

100 // sum of each "priceAmt"

推荐答案

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

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}})

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

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

这篇关于汇总Mongo子文档数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆