gpt4 book ai didi

mongodb - 求和 Mongo 子文档数组

转载 作者:可可西里 更新时间:2023-11-01 09:31:40 25 4
gpt4 key购买 nike

 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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com