Failed to convert a value to a different type
This error occurs within the aggregation framework when an operator like `$convert` or `$toDecimal` fails to convert a value from one type to another. This can happen if the value is in an invalid format or is out of range for the target type.
- 1Using `$toDate` on a string that is not a valid ISO 8601 date format
- 2Using `$toInt` on a string that contains non-numeric characters (e.g., '123a')
- 3An `onError` expression in a conversion operator itself produces an error
- 4Trying to convert `null` or a missing field to a number without specifying an `onError` value
An aggregation pipeline uses `$toInt` to convert a field that contains non-numeric string values.
db.records.insertOne({ value: "100" });
db.records.insertOne({ value: "not-a-number" });
// This pipeline will fail when it processes the second document.
db.records.aggregate([
{ $project: { numericValue: { $toInt: "$value" } } }
]);expected output
MongoServerError: Failed to parse number 'not-a-number' in $toInt
Fix 1
Use `onError` to Handle Failures Gracefully
WHEN You expect that some values may not be convertible.
db.records.aggregate([
{
$project: {
numericValue: {
$convert: {
input: "$value",
to: "int",
onError: 0, // Return 0 if conversion fails
onNull: 0 // Return 0 if the input is null
}
}
}
}
]);Why this works
The `$convert` operator (and other conversion operators) provides an `onError` option that allows you to specify a fallback value to return if the conversion fails. This prevents the entire aggregation from failing.
Fix 2
Pre-filter Documents with `$type`
WHEN You only want to process documents where the type is already correct.
db.records.aggregate([
{ $match: { value: { $type: "string" } } },
// ... rest of pipeline
]);Why this works
Add a `$match` stage at the beginning of your pipeline to filter out documents that do not have the expected data type, ensuring that later conversion stages do not fail.
Fix 3
Cleanse the Data
WHEN The data is consistently in the wrong format.
Why this works
If the data is supposed to be numeric but is stored as a string, perform a one-time migration to update the data to the correct type. This fixes the root cause rather than repeatedly handling it in every query.
✕ Read all data into the application and perform conversions there
This is highly inefficient. The aggregation framework is optimized for data transformation and should be used whenever possible. Moving large datasets to the client for conversion adds network overhead and application complexity.
mongodb/mongo src/mongo/base/error_codes.yml
Aggregation Conversion Operators ↗Content generated with AI assistance and reviewed for accuracy. Found an error? hello@errcodes.dev