$convert (Type Conversion)
Last updated: 2026-10-09
$convert (Type Conversion)
$convert casts a value to a target BSON type and is the master entry point for type conversions. The to parameter accepts double, string, objectId, bool, date, int, long and decimal. Conversion failures throw by default, but onError supplies a fallback; null input yields null by default and onNull overrides that. Typical uses: turning numeric strings into numbers for arithmetic or parsing date strings into dates. Compared with shortcuts like $toInt, $convert adds failure handling.
| Category | Set, Condition & Conversion |
|---|---|
| MongoDB Version | 1.0+ |
| Example Language | mongosh (Shell) |
📝 Syntax
{ $convert: { input: <expression>, to: <type>, onError: <fallback>, onNull: <nullResult> } }
⚙️ Parameters
| input | The value to convert. |
|---|---|
| to | The target type: double/string/objectId/bool/date/int/long/decimal. |
| onError | Optional value returned when the conversion fails. |
| onNull | Optional value returned when the input is null or missing. |
Returns:The converted value; onError/onNull apply on failure or null
▶ Example
Run the commands below in your local mongosh (requires a running mongod):
// $convert: parse string price to a number, fallback 0
db.products.aggregate([
{ $project: {
priceNum: { $convert: { input: '$priceStr', to: 'double', onError: 0 } }
} }
])
Output:
{ '_id': 1, 'priceNum': 19.9 }
{ '_id': 2, 'priceNum': 0 }
📌 Notes
- Failures throw by default; always provide onError in production
- null input yields null; override with onNull
- $toInt/$toDouble etc. are shortcuts for $convert but lack onError
🏷️ Related Tags
💡 Related Cases
More hands-on cases coming soon.
📚 Related Tutorials
❓ FAQ
QWhat happens when $convert fails?
AIt throws and aborts the pipeline; with onError it returns the fallback.
QHow is it different from $toInt?
A$toInt is shorthand for $convert; $convert adds onError/onNull handling.
QWhich types does to accept?
Adouble, string, objectId, bool, date, int, long and decimal.