$toInt (Convert to 32-bit Integer)
Last updated: 2026-10-09
$toInt (Convert to 32-bit Integer)
$toInt converts a value to a 32-bit signed integer (BSON int). It accepts numbers, numeric strings and booleans; null stays null. Typical uses: normalizing integer strings from external systems or rounding floats to integers. Values outside the 32-bit range (about 2.1 billion) throw — use $toLong for big integers. Strings must be integer literals; a fractional string like '4.5' throws. It is the $convert shortcut for to: int.
| Category | Set, Condition & Conversion |
|---|---|
| MongoDB Version | 1.0+ |
| Example Language | mongosh (Shell) |
📝 Syntax
{ $toInt: <expression> }
⚙️ Parameters
| expression | A number, numeric string, or boolean. |
|---|
Returns:An int; null when the input is null
▶ Example
Run the commands below in your local mongosh (requires a running mongod):
// $toInt: parse a quantity string into an integer
db.orders.aggregate([
{ $project: {
qty: { $toInt: '$qtyStr' }
} }
])
Output:
{ '_id': 1, 'qty': 3 }
📌 Notes
- 32-bit range is about 2.1 billion; beyond it throws, so use $toLong for big numbers
- Strings must be integer literals; '4.5' throws
- true becomes 1 and false becomes 0
🏷️ Related Tags
💡 Related Cases
More hands-on cases coming soon.
📚 Related Tutorials
❓ FAQ
QWhat happens beyond the 32-bit range?
AIt throws; switch to $toLong.
QCan the string '4.5' convert?
ANo — it must be an integer literal; fractional strings throw.
QHow does it differ from $toLong?
AWidth differs: $toInt is 32-bit, $toLong is 64-bit.