MongoDB $toBool Operator

Beginner
5 min read
Updated: Oct 2026
3 examples
Live preview

What Is $toBool?

$toBool is a MongoDB aggregation expression that converts a value to a boolean. It is shorthand for { $convert: { input: <expr>, to: "bool" } }.

Remember
$toBool = convert any value → true / false / null

{ $toBool: <expression> }

0 / -0     → false
other nums → true
booleans   → unchanged
strings    → true  (even "" and "false")
null       → null
UsePrefer
Quick convert to boolean$toBool
Convert with onError / onNull$convert
Map string flags like "false"$switch / $cond first

How to Use $toBool in MongoDB

Pick the field, convert it, then filter or project the boolean result.

  1. Choose an expression stage ($addFields or $project).
  2. Pass the value (or field path) to $toBool.
  3. Optional: $match on the new boolean field.
  4. If flags are strings like "false", map them before conversion.
PieceRequired?Role
$toBoolYesConvert expression → boolean (or null)
ExpressionYesField, literal, or nested expression
$convertNoSame conversion with error/null handling

Pseudocode

Pseudocode
for each document:
    x = evaluate(expression)
    if x is null:
        result = null
    else if x is boolean:
        result = x
    else if x is number:
        result = (x != 0)
    else:
        result = true   // strings, arrays, objects, dates, …
    emit { ..., field: result }

Cheat Sheet

Keep these conversion rules handy while writing pipelines.

TopicDetail
TypeAggregation expression (not a find filter)
Syntax{ $toBool: <expression> }
Shorthand for{ $convert: { input: <e>, to: "bool" } }
Numbers0 → false, nonzero → true
StringsAlways true (including "" and "false")
Nullnull → null
Sample check$toBool: 0 → false; $toBool: "false" → true

Live Preview

Pick a value and see what $toBool returns (same rules as MongoDB’s conversion table).

Simulates $toBool conversion rules (same idea as the mongosh examples below).

Result
input = 0
$toBool → false

{ asBool: false }

Worked Walkthrough — Mixed Flags

Three documents store a flag as 0, 1, and "false". Watch how each converts.

Calculation
Documents:
  { name: "zero",       flag: 0 }
  { name: "one",        flag: 1 }
  { name: "text-false", flag: "false" }

$toBool(0)        → false
$toBool(1)        → true
$toBool("false")  → true   ← surprise for beginners!

Only the numeric 0 becomes false.

MongoDB Examples

Insert three flag documents, convert with $toBool, then keep only the false results. Run these in mongosh in order.

Example 1 — Sample Data

Three flags in different shapes: number 0, number 1, and the string "false".

mongosh
db.flags.insertMany([
  { _id: 1, name: "zero", flag: 0 },
  { _id: 2, name: "one", flag: 1 },
  { _id: 3, name: "text-false", flag: "false" }
]);

How the Data Is Stored in MongoDB

After the insert, MongoDB keeps three documents in flags. Run find() to see them:

mongosh
db.flags.find()

Read the rows like this:

FieldExamplesPlain English
_id1, 2, 3Document id
name"zero", …Label for the lesson
flag0, 1, "false"Value we will convert

How It Works

  1. Insert three docs. insertMany stores mixed flag types on purpose.
  2. Types stay as written. 0 and 1 are numbers; "false" is a string.
  3. Ready to convert. The next example runs $toBool on flag.

Example 2 — Convert with $toBool

Goal: add an asBool field for every document.

mongosh
db.flags.aggregate([
  {
    $addFields: {
      asBool: { $toBool: "$flag" }
    }
  }
]);

How It Works

  1. Read each flag. Values come from Example 1.
  2. Convert numbers. 0 → false, 1 → true.
  3. Convert the string. "false" → true because every string is truthy to $toBool.
  4. Keep originals. $addFields adds asBool without removing flag.

Example 3 — Filter False Values

Convert, then keep only documents where asBool is false (only the numeric zero).

mongosh
db.flags.aggregate([
  {
    $addFields: {
      asBool: { $toBool: "$flag" }
    }
  },
  {
    $match: { asBool: false }
  }
]);

How It Works

  1. Same conversion. Stage one builds asBool like Example 2.
  2. Filter on the boolean. $match: { asBool: false } keeps only false results.
  3. String “false” is excluded. It converted to true, so it does not pass the match.
  4. Lesson. For string flags, map "false" / "" with $switch before relying on $toBool.

Edge Cases & Pitfalls

Check these before using $toBool in production pipelines.

strings

"false" and "" become true

Every string converts to true. Do not treat string flags as JavaScript truthiness.

null

Null stays null

$toBool: null returns null, not false. Handle missing flags if you need a default.

zero

Only numeric zero is false among numbers

0 / -0 → false; any other number → true.

errors

Need onError? Use $convert

$toBool has no fallback hooks. Use $convert with onError / onNull when conversions may fail.

Performance Notes

ApproachCostBest for
$toBoolPer-document convertNormalizing mixed flag types
$toBool + $matchConvert then filterBoolean gates in pipelines
$convert + fallbacksSlightly more workUnsafe / nullable inputs

Type conversion is cheap. Prefer storing real booleans when you can, so you do not convert on every query. Filter early with $match when only some docs need the flag.

Key Takeaways

  • Role: convert a value to true / false (or null).
  • Numbers: 0 → false, nonzero → true.
  • Strings: always true—even "false".
  • Shorthand: same as $convert to "bool".

One line: $toBool answers “is this value boolean-true in MongoDB’s rules?”—remember strings are always true.

Frequently Asked Questions

$toBool converts a value to a boolean inside an aggregation pipeline. Use it in stages such as $project and $addFields.
0 and -0 become false. Any other number becomes true.
No. Every string—including "false" and the empty string ""—converts to true. Treat string flags carefully, or map them with $switch / $cond before $toBool.
$toBool is shorthand for { $convert: { input: <expr>, to: "bool" } }. Use $convert when you need onError or onNull fallbacks.
$toBool returns null when the input is null. It does not throw an error.
Similar for numbers and booleans, but not identical for strings: in MongoDB, "" and "false" both become true.

Next: $toDate

Convert values to dates in an aggregation pipeline.

$toDate tutorial →

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.

9 people found this page helpful