Introduction to MongoDB $toDecimal Operator

The $toDecimal operator in MongoDB is used to convert a given value to a decimal number.

Syntax

The syntax for the $toDecimal operator is as follows:

{ $toDecimal: <expression> }

Here, <expression> is a MongoDB expression whose result will be converted to a decimal number.

Use Cases

The $toDecimal operator is used to convert a string or other data type to a decimal number. Common use cases include:

  • Converting string values to decimal numbers for numerical comparison and calculation.
  • Converting other data types to decimal numbers for calculation and aggregation operations.

Example

Assume there is an orders collection containing the following documents:

{ "_id": 1, "total": "123.45" }
{ "_id": 2, "total": "789.01" }

The $toDecimal operator can be used to convert the values of the total field to decimal numbers and calculate the total amount of all orders:

db.orders.aggregate([
  {
    $group: {
      _id: null,
      totalAmount: { $sum: { $toDecimal: "$total" } }
    }
  }
])

After executing the above aggregation operation, the following result is obtained:

{ "_id" : null, "totalAmount" : NumberDecimal("912.46") }

Conclusion

The $toDecimal operator is a commonly used data type conversion operator in MongoDB, which can convert a string or other data type to a decimal number for calculation and aggregation operations.