Introduction to MongoDB $toDouble Operator
$toDouble
is an aggregation operator in MongoDB used to convert the value of an expression to a double-precision floating-point number.
Syntax
The syntax of $toDouble
is as follows:
{ $toDouble: <expression> }
Here, <expression>
is an expression of any type, such as a field name, constant, or other operator.
Use Cases
In MongoDB’s aggregation operations, numerical calculations such as summation, averaging, and finding maximum values are often required. In such cases, it is necessary to convert the data to double-precision floating-point numbers for calculations. This is where the $toDouble
operator comes in handy.
Example
Assume that there is a students
collection containing students’ grade information, as shown below:
{ "_id" : 1, "name" : "Alice", "score" : "95" }
{ "_id" : 2, "name" : "Bob", "score" : "85" }
{ "_id" : 3, "name" : "Charlie", "score" : "92" }
If you need to calculate the average score of students, you need to convert the score
field to a double-precision floating-point number first. You can use the $toDouble
operator for this conversion, as shown in the following example code:
db.students.aggregate([
{ $group: { _id: null, avgScore: { $avg: { $toDouble: "$score" } } } }
])
Running the above code will produce the following result:
{ "_id" : null, "avgScore" : 90.66666666666667 }
Here, $toDouble: "$score"
converts the value of the score
field to a double-precision floating-point number.
Conclusion
$toDouble
is a commonly used operator in MongoDB, used to convert the value of an expression to a double-precision floating-point number. It is typically used for numerical calculations in aggregation operations.