$toBool (aggregation)

Definition

  • $toBool

New in version 4.0.

Converts a value to a boolean.

$toBool has the following syntax:

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

The $toBool takes any valid expression.

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

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

See also

$convert

Behavior

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

Input TypeBehavior
BooleanNo-op. Returns the boolean value.
DoubleReturns true if not zero.Return false if zero.
DecimalReturns true if not zero.Return false if zero.
IntegerReturns true if not zero.Return false if zero.
LongReturns true if not zero.Return false if zero.
ObjectIdReturns true.
StringReturns true.
DateReturns true.

The following table lists some conversion to boolean examples:

ExampleResults
{$toBool: false}false
{$toBool: 1.99999}true
{$toBool: NumberDecimal("5")}true
{$toBool: NumberDecimal("0")}false
{$toBool: 100}true
{$toBool: ISODate("2018-03-26T04:38:28.044Z")}true
{$toBool: "false"}true
{$toBool: ""}true
{$toBool: null}null

Example

Create a collection orders with the following documents:

  1. db.orders.insert( [
  2. { _id: 1, item: "apple", qty: 5, shipped: true },
  3. { _id: 2, item: "pie", qty: 10, shipped: 0 },
  4. { _id: 3, item: "ice cream", shipped: 1 },
  5. { _id: 4, item: "almonds", qty: 2, shipped: "true" },
  6. { _id: 5, item: "pecans", shipped: "false" }, // Note: All strings convert to true
  7. { _id: 6, item: "nougat", shipped: "" } // Note: All strings convert to true
  8. ])

The following aggregation operation on the orders collectionconverts the shipped to a boolean value before finding theunshipped orders:

  1. // Define stage to add convertedShippedFlag field with the converted shipped value
  2. // Because all strings convert to true, include specific handling for "false" and ""
  3.  
  4. shippedConversionStage = {
  5. $addFields: {
  6. convertedShippedFlag: {
  7. $switch: {
  8. branches: [
  9. { case: { $eq: [ "$shipped", "false" ] }, then: false } ,
  10. { case: { $eq: [ "$shipped", "" ] }, then: false }
  11. ],
  12. default: { $toBool: "$shipped" }
  13. }
  14. }
  15. }
  16. };
  17.  
  18. // Define stage to filter documents and pass only the unshipped orders
  19.  
  20. unshippedMatchStage = {
  21. $match: { "convertedShippedFlag": false }
  22. };
  23.  
  24. db.orders.aggregate( [
  25. shippedConversionStage,
  26. unshippedMatchStage
  27. ])

The operation returns the following document:

  1. { "_id" : 2, "item" : "pie", "qty" : 10, "shipped" : 0, "convertedShippedFlag" : false }
  2. { "_id" : 5, "item" : "pecans", "shipped" : "false", "convertedShippedFlag" : false }
  3. { "_id" : 6, "item" : "nougat", "shipped" : "", "convertedShippedFlag" : false }

Note

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