The $convert operator changes a value from one BSON type to another during aggregation. Use it when imported data stores numbers as strings, dates as text, or when you need safe fallbacks for bad values.
01
Type Conversion
String → int, etc.
02
Syntax
input, to, onError.
03
onNull
Handle missing data.
04
$project Stage
Clean field types.
05
Use Cases
Imports, math, dates.
06
vs $toInt
Flexible vs shorthand.
Fundamentals
Definition and Usage
In MongoDB’s aggregation framework, the $convert operator converts an expression to a specified BSON type. For example, turn a string price "29.99" into a number for sorting and arithmetic, or parse an ISO date string into a proper date type.
💡
Beginner Tip
If conversion fails and you did not set onError, the aggregation may error. Always add onError and onNull when working with messy or imported data.
Foundation
📝 Syntax
The $convert operator takes an object with at least input and to:
onError catches invalid strings like "bad". onNull handles missing fields. Both fall back to 0 so the pipeline continues and lineTotal can still be computed.
Example 3 — Convert Number to String
Format a numeric score as a string for display or concatenation:
Once converted to date, you can sort chronologically, filter by year, or group by month. Invalid date strings return null via onError.
Applications
🚀 Use Cases
Data import cleanup — normalize CSV or JSON fields stored as strings into proper numeric or date types.
Safe arithmetic — convert string prices and quantities before $multiply, $sum, or $avg.
Reporting — cast values to strings for labels, or to doubles for chart-ready numeric series.
Schema migration — transform legacy documents in-place during aggregation without rewriting the whole collection.
🧠 How $convert Works
1
MongoDB evaluates input
The input expression is resolved per document. If null or missing, onNull applies.
Input
2
$convert attempts the cast
MongoDB tries to convert to the to type. On failure, onError is returned (or the pipeline errors).
Convert
3
The typed value is stored
The result is written to the field you define in $project or $addFields.
Output
=
📚
Correct BSON type
Ready for math, sorting, date ranges, and type-safe downstream stages.
Wrap Up
Conclusion
The $convert operator is essential for cleaning and transforming data types inside MongoDB aggregation pipelines. It gives you explicit control over target types and safe fallbacks through onError and onNull.
For clean data, shorthand operators like $toInt and $toDouble are fine. For imports, legacy schemas, or ETL jobs, prefer $convert with error handling so one bad field does not break the entire pipeline.
Pick the narrowest target type (int vs double) for your use case
Convert types before math operators like $multiply or $sum
Use $toInt / $toString when data is already validated
Test edge cases: empty strings, "null", and non-numeric text
❌ Don’t
Assume string numbers convert without validation on production data
Forget that failed conversion errors the pipeline without onError
Confuse onNull (missing input) with onError (invalid value)
Convert to date without checking the string format first
Chain unnecessary conversions — convert once, then reuse the field
Summary
Key Takeaways
Knowledge Unlocked
Five things to remember about $convert
Use these points when casting types in MongoDB.
5
Core concepts
📚01
Type Casting
Change BSON types.
Purpose
📝02
input + to
Required fields.
Syntax
⚠03
onError
Invalid value fallback.
Safety
🛠04
onNull
Missing field fallback.
Safety
🔄05
vs $toInt
Full vs shorthand.
Important
❓ Frequently Asked Questions
$convert transforms a value from one BSON type to another inside an aggregation pipeline. You specify the input expression and the target type with the to field.
{ $convert: { input: <expression>, to: <type>, onError: <expression>, onNull: <expression> } }. Only input and to are required.
Common targets include double, string, objectId, bool, date, int, long, decimal, regex, and timestamp. Use the string name for the to field, such as "int" or "date".
onNull runs when the input is null or missing. onError runs when the conversion itself fails, such as converting "abc" to int.
$toInt, $toString, and similar operators are shorthand for common conversions. Use $convert when you need onError, onNull, or less common target types.