MongoDB - total amount

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

I am trying 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 for verification, digital data is really stored and simply not summed up: db.orders.find()[0].total_price this leads to 8.99

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

Thanks in advance.

+4
source share
1 answer

$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 it yourself, as described in Mongo, convert all numeric fields that are stored as strings , but this will be slow.

I would advise you to make sure that your application stores numbers as int / long / float, and that you are writing script iterators over all of your documents and updating the value. I would also suggest adding a function request to https://jira.mongodb.org/browse/SERVER to add a statement that converts a string to a number.

+7
source

Source: https://habr.com/ru/post/1496069/


All Articles