Introduction to MongoDB $toBool Operator

$toBool is a built-in operator in MongoDB used to convert a specified value to a Boolean value (true or false).

Syntax

The syntax of the $toBool operator is as follows:

{ $toBool: <expression> }

Here, <expression> is the expression that needs to be converted to a Boolean value.

Use Cases

In MongoDB, sometimes it is necessary to convert the value of a field to a Boolean value for logical operations and other purposes. For example, during aggregation operations, $toBool can be used to convert the value of a field to a Boolean value, and then perform logical operations.

Example

Assume there is a users collection containing the following documents:

{ "_id" : 1, "name" : "Alice", "age" : 20, "is_student" : "true" }
{ "_id" : 2, "name" : "Bob", "age" : 25, "is_student" : "false" }
{ "_id" : 3, "name" : "Charlie", "age" : 30, "is_student" : "true" }

Now, we need to count the number of users who are students and aged 25 years or above. The following aggregation operation can be used to achieve this:

db.users.aggregate([
  {
    $match: {
      age: { $gte: 25 },
      is_student: { $eq: { $toBool: "$is_student" } }
    }
  },
  {
    $count: "count"
  }
])

The above aggregation operation first filters out users who are 25 years or older, then uses $toBool to convert the value of the is_student field to a Boolean value, and checks if it is true. Finally, it counts the number of users who meet the criteria.

Conclusion

The $toBool operator is a commonly used built-in operator in MongoDB that is used to convert a specified value to a Boolean value. It is useful in scenarios such as aggregation operations where the value of a field needs to be converted to a Boolean value for logical operations.