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?