MongoDB $convert Operator

Beginner
5 min read
Updated: Oct 2026
3 examples
Live preview

What Is $convert?

$convert is a MongoDB aggregation expression that changes a value from one BSON type to another. You can also handle bad data with optional onError and onNull fallbacks.

Remember
$convert = change type safely

{
  $convert: {
    input: <expression>,
    to: "<type>",        // "int", "double", "string", ...
    onError: <value>,    // optional
    onNull: <value>      // optional
  }
}

input + to → required
bad convert → error (unless onError)
null/missing → null (unless onNull)
UsePrefer
Convert with error / null handling$convert
Simple convert, defaults OK$toInt / $toString
Check current type$type

How to Use $convert in MongoDB

Pick the input field, the target type, then decide what happens on failure or null.

  1. Choose an expression stage ($addFields or $project).
  2. Set input to the field or expression to convert.
  3. Set to to the target type string (for example "int" or "double").
  4. Optional: add onError and onNull so dirty data does not stop the pipeline.
PieceRequired?Role
inputYesValue to convert
toYesTarget type ("int", "double", "string", …)
onErrorNoFallback when conversion fails
onNullNoFallback when input is null or missing

Pseudocode

Pseudocode
for each document:
    value = evaluate(input)
    if value is null or missing:
        result = onNull if provided else null
    else:
        try:
            result = convert(value, to)
        catch error:
            if onError provided:
                result = onError
            else:
                fail pipeline
    emit { ..., field: result }

Cheat Sheet

Keep these facts handy while converting types.

TopicDetail
TypeAggregation expression (not a find filter alone)
Syntax{ $convert: { input, to, onError?, onNull? } }
Common to values"int", "double", "string", "bool", "date", "decimal"
String → number{ $convert: { input: "$price", to: "double" } }
Safe convertAdd onError / onNull for dirty data
Shorthand$toInt, $toString, … when defaults are fine
No onErrorFailed convert stops the aggregation

Live Preview

Simulate converting a value to int with onError: 0 and onNull: 0.

Same idea as the mongosh examples: convert to int, use 0 when the value is bad or null.

Result
input = "5"
to = "int"
path → success
result → 5

{ qtyInt: 5 }

Worked Walkthrough — String Quantity to Int

Stored qty is a string. We convert it to int, with 0 as the fallback for errors and nulls.

Calculation
Rule:
  $convert(input → "int", onError: 0, onNull: 0)

"5"   → valid   → 5
"10"  → valid   → 10
"abc" → error   → onError → 0
null  → null    → onNull  → 0

Without onError, "abc" would stop the whole pipeline.

MongoDB Examples

We use a small orders collection where some numbers are stored as strings (and one qty is null). First we convert clean values, then we add safe fallbacks. Insert the sample data once in mongosh.

Example 1 — Sample Data

Imagine four orders. Quantity is stored as a string (or null). We save them in a collection named orders.

mongosh
db.orders.insertMany([
  { _id: 1, item: "apple",  qty: "5" },
  { _id: 2, item: "orange", qty: "10" },
  { _id: 3, item: "banana", qty: "abc" },
  { _id: 4, item: "pear",   qty: null }
]);

How the Data Is Stored in MongoDB

After the insert, MongoDB keeps four documents in orders. Run find() to see them:

mongosh
db.orders.find()

Read those documents like this:

Field in MongoDBExamplePlain English
_id1 … 4Order id for this lesson
item"apple"Product name
qty"5" or nullQuantity stored as string / null (dirty data)
Picture
Convert qty → int:

  "5"   →  5     (success)
  "10"  →  10    (success)
  "abc" →  error (needs onError)
  null  →  null  (needs onNull)

Goal: get numbers we can add / compare.

How It Works

  1. Insert once. insertMany adds four order documents.
  2. MongoDB stores types as written. "5" is a string; null is null—not an int yet.
  3. find() shows the same shape. What you inserted is what you get back—ready for $convert next.

Example 2 — Convert Clean Strings to Int

Goal: convert qty to int for the first two (clean) orders. Filter first so bad values do not break the pipeline.

mongosh
db.orders.aggregate([
  { $match: { _id: { $in: [1, 2] } } },
  {
    $addFields: {
      qtyInt: {
        $convert: {
          input: "$qty",
          to: "int"
        }
      }
    }
  }
]);

How It Works

  1. Filter first. $match keeps only clean rows (_id 1 and 2).
  2. Read the string. input: "$qty" is still "5" / "10".
  3. Change the type. to: "int" turns those strings into integers 5 and 10.
  4. Keep originals. $addFields adds qtyInt; the string qty stays too.

Example 3 — Safe Convert with onError / onNull

Same collection, all four rows. Bad strings and nulls become 0 instead of crashing the pipeline.

mongosh
db.orders.aggregate([
  {
    $addFields: {
      qtyInt: {
        $convert: {
          input: "$qty",
          to: "int",
          onError: 0,
          onNull: 0
        }
      }
    }
  }
]);

How It Works

  1. Same stored documents. Still using all four orders from Example 1.
  2. Success path. "5" and "10" convert normally to 5 and 10.
  3. onError. "abc" cannot become an int, so MongoDB returns 0.
  4. onNull. null uses the null fallback—also 0—and the pipeline keeps running.

Edge Cases & Pitfalls

Check these before converting types in production pipelines.

errors

No onError means pipeline stop

A single bad value can fail the whole aggregation. Add onError when data quality is imperfect.

null

Null is not an error

Null / missing uses onNull (or returns null). It does not call onError.

types

Not every pair converts

Unsupported conversions fail. Check the target type and sample values before shipping.

short

Shorthand loses fallbacks

$toInt is shorter but has no onError / onNull. Use $convert when you need those knobs.

Performance Notes

ApproachCostBest for
$convertPer-document castDirty or mixed-type fields
$toInt / $toStringSame cast, less typingTrusted clean data
Store correct typesNo runtime convertHot paths / large collections

Conversion is cheap per document, but fixing types at write time is better for large collections. Filter early with $match when only some rows need a cast.

Key Takeaways

  • Role: change a value’s BSON type in aggregation.
  • Required: input and to.
  • Safe mode: onError for bad values, onNull for null/missing.
  • Shorthand: use $toInt / $toString when fallbacks are not needed.

One line: $convert answers “turn this value into that type—and what if it fails?”

Frequently Asked Questions

$convert changes a value from one BSON type to another inside an aggregation pipeline. You pass input and the target type with to.
Use { $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, and decimal. Pass the type as a string such as "int" or "date".
onNull runs when input is null or missing. onError runs when the conversion fails, such as turning "abc" into an int.
$toInt, $toString, and similar helpers are shorthand for common conversions. Prefer $convert when you need onError, onNull, or less common target types.
The aggregation throws an error and stops. Add onError to return a fallback instead.

Next: $cos

Compute the cosine of an angle in an aggregation pipeline.

$cos tutorial →

About the author

Mari Selvan M P
Mari Selvan M P 🔗

Developer, cloud engineer, and technical writer

  • Experience 12 years building web and cloud systems
  • Focus Full Stack Development, AWS, and Developer Education

I write practical tutorials so students and working developers can learn by doing—from databases and APIs to deployment on AWS.

9 people found this page helpful