gpt4 book ai didi

mongodb - 汇总 Mongo 子文档的字段

转载 作者:可可西里 更新时间:2023-11-01 09:36:47 28 4
gpt4 key购买 nike

给定以下数据库的集合:

> db.collection.find()
{ "_id" : 1, "results" : { "record" : { "price" : 100 } } }
{ "_id" : 2, "results" : { "record" : { "price" : 200 } } }
{ "_id" : 3, "results" : { "record" : { "price" : 300 } } }

如何使用聚合(或 map-reduce)来获取每个 results.record.price 字段的总和?

> db.collection.aggregate( {$group : { _id:"", "results.record.price" : {$sum : "$results.record.price"}}}, {$project:{_id: 0, "results.record.price" : "$results.record.price"}})
Error: Printing Stack Trace
at printStackTrace (src/mongo/shell/utils.js:37:15)
at DBCollection.aggregate (src/mongo/shell/collection.js:897:9)
at (shell):1:15
Mon Oct 28 20:15:24.065 aggregate failed: {
"errmsg" : "exception: the group aggregate field name 'results.record.price' cannot be used because $group's field names cannot contain '
.'",
"code" : 16414,
"ok" : 0
} at src/mongo/shell/collection.js:898

最佳答案

试试这个。

db.collection.aggregate({$group : {_id: "", total : {$sum: "$results.record.price"}}}, {$project: {_id: 0, total: 1}})

关于mongodb - 汇总 Mongo 子文档的字段,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19647475/

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