16. String, Numeric, and Type Conversion Expressions

Imported data may contain numeric strings or dates stored as strings. Conversion operators include $toInt, $toLong, $toDouble, $toDecimal, $toString, $toDate, and $convert.

$convert supports onError and onNull, allowing a pipeline to define behavior for malformed or missing values. Conversion is not validation: a converted value may still violate a business rule. For financial calculations, consider Decimal128 and consistent decimal arithmetic. String expressions such as $toLower, $toUpper, $trim, $concat, and $split can normalize text.

Investigate null conversion results

A null result may indicate missing, null, or malformed data. Count and investigate invalid records instead of silently treating them as zero.

Code Example
db.importedOrders.aggregate([
  {
    $set: {
      amountDecimal: { $convert: { input: "$amount", to: "decimal", onError: null, onNull: null } },
      normalizedLabel: { $toLower: { $trim: { input: { $ifNull: ["$label", ""] } } } }
    }
  },
  { $project: { amount: 1, amountDecimal: 1, label: 1, normalizedLabel: 1 } }
]);
Key Takeaways
  • Conversion operators normalize imported data.
  • $convert supports error and null handling.
  • Decimal128 may be appropriate for money.
  • Conversion does not replace validation.
Knowledge Check

Which operator supports both onError and onNull?