Type conversion operators

Introduced in MongoDB 4.0, type conversion operators allow us to convert a value to a specified type. The generic syntax of the command is as follows:

{
   $convert:
      {
         input: <expression>,
         to: <type expression>,
         onError: <expression>,  // Optional.
         onNull: <expression>    // Optional.
      }
}

In this syntax, input and to (the only mandatory arguments) can be any valid expression. In its simplest form, we could, for example, have the following:

$convert: { input: "true", to: "bool" } 

This converts a string with the value true to the Boolean value true.

The onError phrase can again be any valid expression, and specifies the value that MongoDB will return if it encounters an error during conversion, including unsupported type conversions. Its default behavior is to throw an error and stop processing.

The onNull phrase can also be any valid expression, and specifies the value that MongoDB will return if the input is null or missing. The default behavior is to return null.

MongoDB also provides some helper functions for the most common $convert operations. These functions are as follows:

  • $toBool
  • $toDate
  • $toDecimal
  • $toDouble
  • $toInt
  • $toLong
  • $toObjectId
  • $toString

 

These are even simpler to use. We could rewrite the previous example as the following:

{ $toBool: "true" }
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset