MongoDB $toBool Operator

Beginner
⏱️ 8 min read
📚 Updated: Jul 2026
🎯 4 Examples
Type Conversion

What You’ll Learn

The $toBool operator converts values to boolean (true or false) in MongoDB aggregation pipelines. Use it to normalize mixed-type flags, clean imported data, and prepare fields for conditional logic.

01

Boolean Conversion

Values to true/false.

02

Syntax

One expression.

03

Conversion Rules

Numbers, strings, arrays.

04

$project Stage

Add boolean fields.

05

Use Cases

Flags, filters, cleanup.

06

vs $convert

Shorthand vs flexible.

Definition and Usage

In MongoDB’s aggregation framework, the $toBool operator converts an expression to a boolean value. It is part of the type-conversion family alongside $toInt, $toString, and $toDate. Real-world data often stores flags as numbers (0/1), strings ("yes"/""), or actual booleans — $toBool helps normalize them.

$toBool is shorthand for { $convert: { input: <expression>, to: "bool" } }. It follows MongoDB’s built-in boolean conversion rules rather than JavaScript’s truthiness rules.

💡
Beginner Tip

The string "false" converts to true because it is non-empty. Use $cond or $eq when you need to interpret specific string values like "yes" or "no".

📝 Syntax

The $toBool operator takes one expression:

mongosh
{ $toBool: <expression> }

Literal Examples

mongosh
{ $toBool: 1 }
// Result: true

{ $toBool: 0 }
// Result: false

{ $toBool: "" }
// Result: false

{ $toBool: "hello" }
// Result: true

{ $toBool: "$isActive" }
// Convert the isActive field

Conversion Rules

  • null — returns null.
  • Boolean — returns the same boolean value.
  • Number0, -0, and NaN become false; all other numbers become true.
  • String — empty string "" becomes false; any non-empty string becomes true.
  • Array — empty array becomes false; non-empty array becomes true.
  • Date, ObjectId, document — non-null values become true.
  • Use inside $project, $addFields, or $set.

💡 $toBool vs $convert

$toBool — shorthand: { $toBool: "$field" }
$convert — full form: { $convert: { input: "$field", to: "bool" } }
Use $convert when you need onError or onNull fallbacks
See the $convert operator tutorial for flexible type conversion

⚡ Quick Reference

QuestionAnswer
Operator typeAggregation expression operator (type conversion)
Syntax{ $toBool: <expression> }
Equivalent{ $convert: { input: <expr>, to: "bool" } }
0 / "" / []All convert to false
null inputReturns null
Common stages$project, $addFields, $set
Field
{
  $toBool: "$active"
}

Convert a field

Zero
{
  $toBool: 0
}

Returns false

Non-zero
{
  $toBool: 42
}

Returns true

Empty str
{
  $toBool: ""
}

Returns false

Examples Gallery

Normalize mixed-type user flags, convert numeric 0/1 values, and filter documents after boolean conversion.

📚 User Settings

Start with a users collection containing mixed-type active flags and normalize them with $toBool.

Sample Input Documents

Suppose you have a users collection where the active field is stored in different formats:

mongosh
[
  { "_id": 1, "name": "Alice", "active": true },
  { "_id": 2, "name": "Bob",   "active": 0 },
  { "_id": 3, "name": "Carol", "active": 1 },
  { "_id": 4, "name": "Dave",  "active": "" },
  { "_id": 5, "name": "Eve",   "active": "enabled" }
]

Example 1 — Basic $toBool on a Field

Add a normalized isActive boolean field:

mongosh
db.users.aggregate([
  {
    $project: {
      name: 1,
      active: 1,
      isActive: { $toBool: "$active" }
    }
  }
])

How It Works

  • Alice: boolean true stays true.
  • Bob: number 0 becomes false.
  • Carol: number 1 becomes true.
  • Dave: empty string becomes false.
  • Eve: non-empty string "enabled" becomes true.

📈 Practical Patterns

Handle numeric flags, empty arrays, and filter active users after conversion.

Example 2 — Convert Numeric 0/1 Flags

Legacy systems often store booleans as integers. Normalize them for modern queries:

mongosh
db.products.aggregate([
  {
    $addFields: {
      inStock: { $toBool: "$stockCount" }
    }
  }
])

// stockCount: 0   → inStock: false
// stockCount: 15  → inStock: true
// stockCount: -3  → inStock: true (non-zero)

How It Works

Only zero converts to false. Any non-zero number — positive or negative — converts to true.

Example 3 — Arrays and Empty Values

Check whether a field has content by converting arrays to boolean:

mongosh
db.orders.aggregate([
  {
    $project: {
      orderId: 1,
      hasItems: { $toBool: "$items" },
      hasNotes: { $toBool: "$notes" }
    }
  }
])

// items: ["a", "b"]  → hasItems: true
// items: []          → hasItems: false
// notes: ""           → hasNotes: false
// notes: "rush"       → hasNotes: true

How It Works

Empty arrays and empty strings both become false. Non-empty arrays and strings become true.

Example 4 — Filter After Boolean Conversion

Convert first, then filter to active users only:

mongosh
db.users.aggregate([
  {
    $addFields: {
      isActive: { $toBool: "$active" }
    }
  },
  {
    $match: {
      isActive: true
    }
  },
  {
    $project: {
      name: 1,
      isActive: 1
    }
  }
])

How It Works

$addFields normalizes the flag, then $match filters on the clean boolean value.

Bonus — String "false" Is Still true

A common mistake: expecting the string "false" to convert to boolean false:

mongosh
db.settings.aggregate([
  {
    $project: {
      viaToBool: { $toBool: "$flag" },
      viaCond: {
        $cond: [
          { $eq: [ "$flag", "true" ] },
          true,
          false
        ]
      }
    }
  }
])

// flag: "false"
// viaToBool → true  (non-empty string!)
// viaCond   → false (explicit comparison)

How It Works

$toBool checks emptiness, not meaning. Use $cond with $eq when you need to interpret specific string values.

🚀 Use Cases

  • Data migration cleanup — normalize legacy 0/1 integer flags to proper booleans.
  • Feature flags — convert mixed-type settings fields before conditional logic.
  • Presence checks — test whether strings or arrays are empty with a boolean result.
  • Reporting filters — create a clean boolean field, then filter or group on it.
  • ETL pipelines — prepare boolean columns for export to systems that require strict types.

🧠 How $toBool Works

1

MongoDB reads the expression

The input resolves from a field path, literal, or nested expression in the pipeline.

Input
2

BSON type rules are applied

MongoDB checks the value type and applies boolean conversion rules (zero, empty string, empty array → false).

Convert
3

A boolean result is returned

The output is true, false, or null (for null input).

Output
=

Clean boolean field

Use the result in $match, $cond, or downstream reporting.

Conclusion

The $toBool operator converts values to boolean in MongoDB aggregation pipelines. It is the simplest way to normalize mixed-type flags, but remember its rules differ from JavaScript truthiness — especially for strings like "false".

For conversions that need error handling, use $convert with onError and onNull. Next in the series: $toDate.

💡 Best Practices

✅ Do

  • Use $toBool to normalize 0/1 numeric flags
  • Test with empty strings, zero, and null inputs
  • Pair with $match after conversion for clean filters
  • Use $convert when you need onNull defaults
  • Document conversion rules for your team when cleaning legacy data

❌ Don’t

  • Expect "false" or "0" strings to become false
  • Confuse $toBool with JavaScript truthiness rules
  • Use $toBool as a query filter operator outside expressions
  • Assume null becomes false (it returns null)
  • Skip validation when importing boolean data from external systems

Key Takeaways

Knowledge Unlocked

Five things to remember about $toBool

Use these points when converting values to boolean in MongoDB.

5
Core concepts
📝 02

{ $toBool: x }

One argument.

Syntax
🔢 03

0 / "" / []

All false.

Rules
🛠 04

$project

Normalize flags.

Usage
05

"false" → true

String trap.

Gotcha

❓ Frequently Asked Questions

$toBool converts a value to a boolean inside an aggregation pipeline. It is an aggregation expression operator used in stages like $project and $addFields.
The syntax is { $toBool: <expression> }. The expression can be a field reference like "$active", a literal, or another expression.
Numbers 0 and -0 become false; other numbers become true. An empty string becomes false; any non-empty string becomes true — including the string "false".
$toBool is shorthand for { $convert: { input: <expr>, to: "bool" } }. Use $convert when you need onError or onNull fallbacks for failed conversions.
$toBool returns null when the input is null. It does not throw an error.

Continue the Operator Series

Move on to $toDate for date conversion, or review $convert for flexible type transforms.

Next: $toDate →

About the author

Mari Selvan M P
Mari Selvan M P 🔗

Developer, cloud engineer, and technical writer

  • Experience 12 years building web and cloud systems
  • Focus Full Stack Development, AWS, and Developer Education

I write practical tutorials so students and working developers can learn by doing—from databases and APIs to deployment on AWS.

5 people found this page helpful