$toBool

The `$toBool` operator converts an expression into a Boolean value. Boolean values are returned as is without a conversion. Nonzero numeric values are converted to true while Decimal, Long, Double or Int values of 0 are converted to false. All other data types are converted to true.

Syntax

{
  $toBool: <expression>
}

Parameters

expressionobjectrequired

The specified value to convert into a Boolean value.

Examples

Sample Data

{
  "_id": "0fcc0bf0-ed18-4ab8-b558-9848e18058f4",
  "name": "First Up Consultants | Beverage Shop",
  "location": { "lat": -89.2384 },
  "sales": { "totalSales": 75670 }
}

Convert a Double to Boolean

Convert latitude field from double to boolean.

Positive numeric values are converted to true.

Query:

db.stores.aggregate([{
  $match: { _id: "b0107631-9370-4acd-aafa-8ac3511e623d" }
}, {
  $project: {
    originalLatitude: "$location.lat",
    latitudeAsBool: { $toBool: "$location.lat" }
  }
}])

Output:

[
  {
    "_id": "b0107631-9370-4acd-aafa-8ac3511e623d",
    "originalLatitude": 72.8377,
    "latitudeAsBool": true
  }
]

Convert a String to Boolean

Convert _id field from string to boolean.

String values are converted to true.

Query:

db.stores.aggregate([{
  $match: { _id: "b0107631-9370-4acd-aafa-8ac3511e623d" }
}, {
  $project: {
    originalId: "$_id",
    idAsBool: { $toBool: "$_id" }
  }
}])

Output:

[
  {
    "_id": "b0107631-9370-4acd-aafa-8ac3511e623d",
    "originalId": "b0107631-9370-4acd-aafa-8ac3511e623d",
    "idAsBool": true
  }
]

Related