$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.

CategorySet, Condition & Conversion
MongoDB Version1.0+
Example Languagemongosh (Shell)

📝 Syntax

{ $toBool: <expression> }

⚙️ Parameters

expressionThe 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

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.
Web-Tutorial.com

Web-Tutorial Tech Team

A team of developers maintaining programming tutorials. Each tutorial is written and reviewed by developers with expertise in that field. We work to keep our content accurate and reliable — if you spot an issue, please let us know.

100%

🙏 帮我们做得更好

我们是刚上线的编程教程站,几个人的小团队,精力有限。页面虽经检查,难免还有疏漏——链接失效、排版错乱、内容有误、语言生硬……

如果您发现了,麻烦告诉我们,我们会在收到反馈后第一时间进行修复,再次感谢您的光临 🙏