Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Summing Mongo Sub-documents' field

Tags:

mongodb

Given the following database's collection:

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

How can I use aggregation (or map-reduce) to get the sum of each results.record.price field?

> 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
like image 957
Kevin Meredith Avatar asked Mar 25 '26 18:03

Kevin Meredith


1 Answers

Try this.

db.collection.aggregate({$group : {_id: "", total : {$sum: "$results.record.price"}}}, {$project: {_id: 0, total: 1}})
like image 171
Rafa Avatar answered Mar 28 '26 07:03

Rafa



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!