MongoDB $toBool

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

When you convert a value to a boolean, the result will be true or false, depending on the input value.

Generally, for numeric values, this will return false if the value is zero (0), and true for any other value.

For string, ObjectId, and Date values, it will always return true.

Example

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

{
	"_id" : ObjectId("60133e50c8eb4369cf6ad9d9"),
	"double" : 123.75,
	"string" : "123",
	"boolean" : true,
	"date" : ISODate("2020-12-31T23:30:15.123Z"),
	"integer" : 123,
	"long" : NumberLong(123),
	"decimal" : NumberDecimal("123.75")
}
{
	"_id" : ObjectId("60133e50c8eb4369cf6ad9da"),
	"double" : 0,
	"string" : "",
	"boolean" : false,
	"date" : null,
	"integer" : 0,
	"long" : NumberLong(0),
	"decimal" : NumberDecimal("0.0")
}

We can use the $toBool operator to convert all those types to a boolean. If the input is a boolean, then it simply returns the boolean.

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

Result:

{
	"objectId" : true,
	"double" : true,
	"string" : true,
	"boolean" : true,
	"date" : true,
	"integer" : true,
	"long" : true,
	"decimal" : true
}
{
	"objectId" : true,
	"double" : false,
	"string" : true,
	"boolean" : false,
	"date" : null,
	"integer" : false,
	"long" : false,
	"decimal" : false
}

We can see that all values in the first document returned true, but many in the second document returned false. Also, the date value returned null because it was null to start with.

Errors

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

The $toBool operator is the equivalent of using the $convert operator to convert a value to a boolean.

Here’s an example of using $convert to convert a string to a boolean::

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

Result:

{ "result" : true } 

See MongoDB $convert for more examples.