$toDouble(aggregation)

Definition

  • $toDouble

New in version 4.0.

Converts a value to a double. If the value cannot be converted toan double, $toDouble errors. If the value is null ormissing, $toDouble returns null.

$toDouble has the following syntax:

  1. {
  2. $toDouble: <expression>
  3. }

The $toDouble takes any valid expression.

The $toDouble is a shorthand for the following$convert expression:

  1. { $convert: { input: <expression>, to: "double" } }

Behavior

The following table lists the input types that can be converted to adouble:

Input TypeBehavior
BooleanReturns 0 for false.Returns 1 for true.
DoubleNo-op. Returns the double.
DecimalReturns the decimal value as a double.The decimal value must fall within the minimum andmaximum value for a double.You cannot convert a decimal value whose value is lessthan the minimum double value or is greater than the maximumdouble value.
IntegerReturns the int value as a double.
LongReturns the long value as a double.
StringReturns the numerical value of the string as a double.The string value must be of a base10 numeric value (e.g."-5.5", "123456") and fall within the minimum andmaximum value for a double.You cannot convert a string value of a non-base10number (e.g. "0x6400") or a value that fallsoutside the minimum and maximum value for a double.
DateReturns the number of milliseconds since the epoch thatcorresponds to the date value.

The following table lists some conversion to double examples:

ExampleResults
$toDouble: true1
$toDouble: false0
$toDouble: 2.52.5
$toDouble: NumberInt(5)5
$toDouble: NumberLong(10000)10000
$toDouble: "-5.5"-5.5
$toDouble: ISODate("2018-03-27T05:04:47.890Z")1522127087890

Example

Create a collection weather with the following documents:

  1. db.weather.insert( [
  2. { _id: 1, date: new Date("2018-06-01"), temp: "26.1C" },
  3. { _id: 2, date: new Date("2018-06-02"), temp: "25.1C" },
  4. { _id: 3, date: new Date("2018-06-03"), temp: "25.4C" },
  5. ] )

The following aggregation operation on the weather collectionparses the temp value and converts to a double:

  1. // Define stage to add degrees field with converted value
  2.  
  3. tempConversionStage = {
  4. $addFields: {
  5. degrees: { $toDouble: { $substrBytes: [ "$temp", 0, 4 ] } }
  6. }
  7. };
  8.  
  9.  
  10. db.weather.aggregate( [
  11. tempConversionStage,
  12. ])

The operation returns the following documents:

  1. { "_id" : 1, "date" : ISODate("2018-06-01T00:00:00Z"), "temp" : "26.1C", "degrees" : 26.1 }
  2. { "_id" : 2, "date" : ISODate("2018-06-02T00:00:00Z"), "temp" : "25.1C", "degrees" : 25.1 }
  3. { "_id" : 3, "date" : ISODate("2018-06-03T00:00:00Z"), "temp" : "25.4C", "degrees" : 25.4 }

Note

If the conversion operation encounters an error, the aggregationoperation stops and throws an error. To override this behavior, use$convert instead.