Mongodb how to request a sum string?

I have some data in an order document like:

 { "_id": "...", "orderTotal": { "amount" : "10.99", "unit": "USD"}, "orderTime": "...", ... } { "_id": "...", "orderTotal": { "amount" : "9.99", "unit": "USD"}, "orderTime": "...", ... } { "_id": "...", "orderTotal": { "amount" : "8.99", "unit": "USD"}, "orderTime": "...", ... } 

I want to request orderTotal of all orders by day:

 db.getCollection('order').aggregate([ { '$group' : { '_id': { day: { $dayOfMonth: "$orderTime"}, month: {$month: "$orderTime"}, year: { $year: "$orderTime" }}, 'totalAmount': { $sum: '$itemTotal.amount' }, 'count': { $sum: 1 } } } ]) 

but received:

 { "_id" : { "day" : 12, "month" : 12, "year" : 2016 }, "totalAmount" : 0, "count" : 4607.0 } 

amount is a string. Use parseFloat , but get NaN.

 db.getCollection('order').aggregate([ { '$group' : { '_id': { day: { $dayOfMonth: "$orderTime"}, month: {$month: "$orderTime"}, year: { $year: "$orderTime" }}, 'totalAmount': { $sum: parseFloat('$itemTotal.amount') }, 'count': { $sum: 1 } } } ]) 

got

 { "_id" : { "day" : 12, "month" : 12, "year" : 2016 }, "totalAmount" : NaN, "count" : 4607.0 } 

I cannot update the order document to change itemTotal.amount to float, as well as to other questions:

 db.order.find().forEach(function(data) { db.order.update({ "_id": data._id, "itemTotal.amount": data.itemTotal.amount }, { "$set": { "itemTotal.amount": parseFloat(data.itemTotal.amount) } }); }) 

I do not have rights for this. So how can I get the amount per day?

+5
source share
1 answer

This is not possible with MongoDB 3.4. This function has already been requested, but not yet implemented:

A type conversion mechanism is required to convert strings and numbers

So the only way to solve your problem is to manually execute the totalAmount in javascript ...

+3
source

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


All Articles