MongoDB $toInt

From MongoDB 4.0, you can use the $toInt aggregation pipeline operator to convert a value to an integer.

Most types can be can be converted to an integer, but the ObjectId and Date values can’t.

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

Numeric values such as double and decimal are truncated as required.

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 $toInt operator to convert those fields (except for the _id and date fields) to an integer. If the input is already an integer, then it simply returns the integer.

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

Result:

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

Note that I excluded the date and _id fields from the operation, because these types cannot be converted to an integer.

Errors

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

The $toInt operator is the equivalent of using the $convert operator to convert a value to an integer.

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

db.types.aggregate(
  [
    {
      $project:
        { 
          _id: 0,
          result: 
          {
            $convert: { 
              input: "$date", 
              to: "int",
              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.