mongodb - 求和 Mongo 子文档数组

标签 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//每个“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/

相关文章:

angularjs - 错误 : [$resource:badcfg] Error in resource configuration for action `query` . 预期响应包含一个数组但得到一个对象

MongoDB:在 Map Reduce 期间收集 E11000 重复键错误

javascript - Mongoose $slice 并获取原始大小的数组

mongodb - 如何编码/解码 mongodb 游标?

javascript - 在 map Node.js 中使用 waterfall

mongodb - JEST 和 MongoDB 的异步问题

MongoDB C# 驱动程序不自动映射 pascal 大小写的属性

java - 对 MongoDB 的 java 驱动程序中的重复唯一键错误使用react

javascript - 使用 Mongoose 和/或 underscore.js 实现 Mongo 查询和响应 'GroupBy'

mongodb - InsertMany 在 mongodb 中不起作用