MongoDB $toDouble

From MongoDB 4.0, you can use the $toDouble aggregation pipeline operator to convert a value to a double.

Most types can be can be converted to double, but the ObjectId can’t.

When you convert a Date value to a double, $toDouble returns the number of milliseconds since the epoch that corresponds to the date value.

When you convert a boolean to a double, if the boolean is true, then the double is 1. If the boolean is false, then the double is 0.

Example

Suppose we have a collection called types and it contains the following documents:

{
	"_id" : ObjectId("601340eac8eb4369cf6ad9db"),
	"double" : 123.75,
	"string" : "123",
	"boolean" : true,
	"date" : ISODate("2020-12-31T23:30:15.123Z"),
	"integer" : 123,
	"long" : NumberLong(123),
	"decimal" : NumberDecimal("123.75")
}

We can use the $toDouble operator to convert those types (except for the ObjectId) to a double. If the input is already a double, then it simply returns the double.

db.types.aggregate(
  [
    {
      $project:
        { 
          _id: 0,
          double: { $toDouble: "$double" },
          string: { $toDouble: "$string" },
          boolean: { $toDouble: "$boolean" },
          date: { $toDouble: "$date" },
          integer: { $toDouble: "$integer" },
          long: { $toDouble: "$long" },
          decimal: { $toDouble: "$decimal" }
        }
    }
  ]
).pretty()

Result:

{
	"double" : 123.75,
	"string" : 123,
	"boolean" : 1,
	"date" : 1609457415123,
	"integer" : 123,
	"long" : 123,
	"decimal" : 123.75
}

Errors

If you encounter errors, try using the $convert operator instead of $toDouble. The $convert operator allows you to handle errors without affecting the whole aggregation operation.

The $toDouble operator is the equivalent of using the $convert operator to convert a value to a double.

Here’s an example of using $convert to try to convert an ObjectId to a double (which results in an error):

db.types.aggregate(
  [
    {
      $project:
        { 
          _id: 0,
          result: 
          {
            $convert: { 
              input: "$_id", 
              to: "double",
              onError: "An error occurred",
              onNull: "Input was null or empty" 
            }
          }
        }
    }
  ]
)

Result:

{ "result" : "An error occurred" } 

Using $convert allowed us to specify the error message to use when the error occurred, and it didn’t halt the whole aggregation operation.

See MongoDB $convert for more examples.