Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Selected Reading
Why does my MongoDB group query return always 0 in float conversion? How to fix it?
When MongoDB group queries return 0 during float conversion, it's typically because string values aren't being properly converted to numbers. Use parseFloat() or MongoDB's $toDouble operator to convert string numbers to actual numeric types.
Syntax
// Using parseFloat() in forEach
db.collection.find({}).forEach(function(doc) {
doc.field = parseFloat(doc.field);
db.collection.save(doc);
});
// Using $toDouble in aggregation
db.collection.aggregate([
{ $addFields: { "field": { $toDouble: "$field" } } }
]);
Sample Data
db.demo523.insertOne({
"details": {
"values": "-0.45"
}
});
{
"acknowledged": true,
"insertedId": ObjectId("5e89b7efb3fbf26334ef611f")
}
db.demo523.find();
{ "_id": ObjectId("5e89b7efb3fbf26334ef611f"), "details": { "values": "-0.45" } }
Method 1: Using parseFloat() with forEach
Convert string values to float numbers using parseFloat() ?
db.demo523.find({}).forEach(function(d) {
d.details.values = parseFloat(d.details.values);
db.demo523.save(d);
});
Verify the conversion ?
db.demo523.find();
{ "_id": ObjectId("5e89b7efb3fbf26334ef611f"), "details": { "values": -0.45 } }
Method 2: Using $toDouble in Aggregation
Use MongoDB's built-in $toDouble operator for safer conversion ?
db.demo523.aggregate([
{
$addFields: {
"details.values": { $toDouble: "$details.values" }
}
},
{ $out: "demo523" }
]);
Key Points
- String values like
"-0.45"must be converted to numeric types before mathematical operations -
parseFloat()works in JavaScript operations but$toDoubleis preferred in aggregation pipelines - Always verify data types after conversion to ensure proper numeric operations
Conclusion
MongoDB group queries return 0 in float conversion when string values aren't properly converted to numbers. Use parseFloat() with forEach() or $toDouble in aggregation pipelines for reliable numeric conversions.
Advertisements
