Mongo子文档字段求和

3

考虑以下数据库集合:

> 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
1个回答

3

试一试。

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

_id: "" 是什么意思?谢谢帮助。 - Kevin Meredith
@kevin _id 是群组标识符。在这种情况下,由于它是常量,即空字符串,因此处理的每个记录都将合并到一个由该空字符串标识的单个群组中。您可以使用其他常量,如 null"a" 等。 - Rafa Viotti
请您检查一下这个链接 - https://dev59.com/lnjZa4cB1Zd3GeqPfIh_ - Kevin Meredith

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接