汇总Mongo子文档数组

编程入门 行业动态 更新时间:2024-10-22 20:24:05
本文介绍了汇总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子文档数组

本文发布于:2023-11-22 13:21:37,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1617577.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:数组   文档   Mongo

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!