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

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

📝 Syntax

{ $convert: { input: <expression>, to: <type>, onError: <fallback>, onNull: <nullResult> } }

⚙️ Parameters

inputThe value to convert.
toThe target type: double/string/objectId/bool/date/int/long/decimal.
onErrorOptional value returned when the conversion fails.
onNullOptional 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

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

🙏 帮我们做得更好

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

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