MongoDB $convert Operator

Beginner
⏱️ 9 min read
📚 Updated: Jul 2026
🎯 4 Examples
Type Conversion

What You’ll Learn

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.

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.

📝 Syntax

The $convert operator takes an object with at least input and to:

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

Syntax Rules

  • input — the value to convert (field reference, literal, or nested expression).
  • to — target type as a string: "int", "double", "string", "date", "bool", "objectId", "long", "decimal", "timestamp", or "regex".
  • onError — optional fallback when conversion fails (invalid format).
  • onNull — optional fallback when input is null or missing.
  • Use inside $project, $addFields, $set, or $group.
  • Available in MongoDB 4.0+. Shorthand operators like $toInt wrap common cases.

💡 $convert vs $toInt / $toString

$convert — full control with onError and onNull
$toInt — shorthand: { $toInt: "$price" } (errors on failure)
Use $convert for safe ETL; use $toInt when data is already clean

⚡ Quick Reference

QuestionAnswer
Operator typeAggregation expression operator (type conversion)
Required fieldsinput, to
Optional fieldsonError, onNull
Common targetsint, double, string, date, bool
Common stages$project, $addFields, $set
String to int
{
  $convert: {
    input: "$qty",
    to: "int"
  }
}

Parse numeric strings

onError
{
  $convert: {
    input: "$price",
    to: "double",
    onError: 0
  }
}

Fallback on bad data

onNull
{
  $convert: {
    input: "$score",
    to: "int",
    onNull: 0
  }
}

Default for missing

To date
{
  $convert: {
    input: "$createdAt",
    to: "date"
  }
}

Parse date strings

Examples Gallery

Convert string prices to numbers, handle invalid imports safely, and parse date strings with $convert.

📚 Basic Type Conversion

Use an orders collection where some numeric fields were imported as strings.

Sample Input Documents

Suppose you have an orders collection with string quantities and prices:

mongosh
[
  { "_id": ObjectId("609c26812e9274a86871bc6a"), "item": "Widget",  "qty": "5",   "price": "19.99" },
  { "_id": ObjectId("609c26812e9274a86871bc6b"), "item": "Gadget",  "qty": "12",  "price": "8.50"  },
  { "_id": ObjectId("609c26812e9274a86871bc6c"), "item": "Cable",   "qty": "bad", "price": "4.99"  }
]

Example 1 — Convert String to Integer

Turn the qty string into an integer for math and sorting:

mongosh
db.orders.aggregate([
  {
    $project: {
      item: 1,
      qtyInt: {
        $convert: {
          input: "$qty",
          to: "int"
        }
      }
    }
  }
])

How It Works

  • "5" and "12" convert cleanly to integers.
  • "bad" cannot convert to int — add onError to handle this safely.

📈 Safe Conversion Patterns

Use onError and onNull when data quality is uncertain.

Example 2 — Handle Invalid Values with onError

Convert price to double and use 0 when conversion fails:

mongosh
db.orders.aggregate([
  {
    $project: {
      item: 1,
      qtyInt: {
        $convert: {
          input: "$qty",
          to: "int",
          onError: 0,
          onNull: 0
        }
      },
      priceNum: {
        $convert: {
          input: "$price",
          to: "double",
          onError: 0,
          onNull: 0
        }
      },
      lineTotal: {
        $multiply: [
          {
            $convert: {
              input: "$qty",
              to: "int",
              onError: 0,
              onNull: 0
            }
          },
          {
            $convert: {
              input: "$price",
              to: "double",
              onError: 0,
              onNull: 0
            }
          }
        ]
      }
    }
  }
])

How It Works

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:

mongosh
db.students.aggregate([
  {
    $project: {
      name: 1,
      scoreLabel: {
        $convert: {
          input: {
            $concat: [
              "Score: ",
              {
                $convert: {
                  input: "$score",
                  to: "string"
                }
              }
            ]
          },
          to: "string"
        }
      }
    }
  }
])

// Or simply: { $convert: { input: "$score", to: "string" } }

How It Works

Converting numbers to strings is useful before $concat, export formatting, or when downstream systems expect text.

Example 4 — Convert String to Date

Parse ISO date strings stored as text into BSON dates for range queries:

mongosh
db.events.aggregate([
  {
    $project: {
      title: 1,
      eventDate: {
        $convert: {
          input: "$dateString",
          to: "date",
          onError: null,
          onNull: null
        }
      }
    }
  }
])

// dateString: "2024-06-15T10:30:00Z" → ISODate(...)

How It Works

Once converted to date, you can sort chronologically, filter by year, or group by month. Invalid date strings return null via onError.

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

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.

💡 Best Practices

✅ Do

  • Add onError and onNull for messy or imported data
  • 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

Key Takeaways

Knowledge Unlocked

Five things to remember about $convert

Use these points when casting types in MongoDB.

5
Core concepts
📝 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.

Continue the Operator Series

Move on to $cos for trigonometry, or review $cond for conditional logic.

Next: $cos →

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.

5 people found this page helpful