$toBool (Convert to Boolean)
Last updated: 2026-10-09
$toBool (Convert to Boolean)
$toBool converts a value to a boolean. The number 0 becomes false and any non-zero number becomes true; the strings 'true' and 'false' convert directly; dates become true; null stays null. Typical uses: normalizing 0/1 flags from APIs into boolean fields or standardizing truth representations. It is the $convert shortcut for to: bool, without onError — converting invalid values throws.
| Category | Set, Condition & Conversion |
|---|---|
| MongoDB Version | 1.0+ |
| Example Language | mongosh (Shell) |
📝 Syntax
{ $toBool: <expression> }
⚙️ Parameters
| expression | The value to convert. |
|---|
Returns:A boolean; null when the input is null
▶ Example
Run the commands below in your local mongosh (requires a running mongod):
// $toBool: turn a 0/1 flag into a boolean
db.devices.aggregate([
{ $project: {
active: { $toBool: '$enabled' }
} }
])
Output:
{ '_id': 1, 'active': true }
{ '_id': 2, 'active': false }
📌 Notes
- 0 becomes false and non-zero becomes true; the string '0' becomes true
- null input yields null, not false
- Unsupported types throw; guard with $convert onError
🏷️ Related Tags
💡 Related Cases
More hands-on cases coming soon.
📚 Related Tutorials
❓ FAQ
QWhat does the number 0 become?
AIt becomes false; any non-zero number becomes true.
QCan strings convert?
A'true' and 'false' work; other strings throw.
QWhat does null return?
AIt returns null, not false.