Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MongoDB - Aggregate Sum

I am attempting to calculate the total amount of money spent being tracked inside of our database. Each order document contains a field "total_price"

I am attempting to use the following code:

db.orders.aggregate({
    $group: {
        _id: null,
        total: {$sum: "$total_price"}
    }
})

Unfortunately, the only output I get is: { "result" : [ { "_id" : null, "total" : 0 } ], "ok" : 1 }

But to verifiy there is actually numerical data stored, and just not being totaled: db.orders.find()[0].total_price this results in 8.99

Any help would be greatly appreciated. I have very little experience using MongoDB. I've only covered the basics at this point.

Thank you in advance.

like image 259
Michael Avatar asked Mar 23 '23 20:03

Michael


1 Answers

$sum only works with ints, longs and floats. Right now, there is no operator to parse a string into a number, although that would be very useful. You can do this yourself as is described in Mongo convert all numeric fields that are stored as string but that would be slow.

I would suggest you make sure that your application stores numbers as int/long/float, and that you write a script that iterators over all your documents and updates the value. I would also suggest that you add a feature request at https://jira.mongodb.org/browse/SERVER to add an operator that converts a string to a number.

like image 200
Derick Avatar answered Apr 02 '23 21:04

Derick