KeplerGrid guide

Convert mixed BSON field values with MongoDB $convert

Use $convert to standardize a mixed field in an aggregation result. Give failed conversions a separate outcome so a malformed amount cannot be mistaken for a real zero.

Convert raw amounts to Decimal128

Load the practice orders. Open keplergrid_transform_lab.orders in KeplerGrid on a Read only connection. Select Aggregation → JSON, paste the pipeline, and choose Run pipeline.

[
  { "$sort": { "_id": 1 } },
  { "$set": {
    "normalizedAmount": {
      "$convert": {
        "input": "$amountRaw",
        "to": "decimal",
        "onError": "invalid",
        "onNull": null
      }
    }
  } },
  { "$set": {
    "amountCheck": {
      "$switch": {
        "branches": [
          { "case": { "$eq": ["$normalizedAmount", "invalid"] }, "then": "invalid" },
          { "case": { "$eq": ["$normalizedAmount", null] }, "then": "null or missing" }
        ],
        "default": "converted"
      }
    }
  } }
]

onError supplies the sentinel string when the conversion fails. onNull applies when the source is null or absent. The final stage makes the outcome explicit alongside the original amountRaw value.

Check the converted values in KeplerGrid

In Stages, select stage 2 to compare raw inputs with normalizedAmount, then select stage 3 to see the labels. The two successfully converted values are Decimal128. The raw values stay available for checking.

Expected conversion outcomes
OrderNormalized amountAmount check
ORD-10112.50converted
ORD-102"invalid"invalid
ORD-103nullnull or missing
ORD-20110.00converted
ORD-202nullnull or missing

The result field can contain a number, a string, or null in this diagnostic pipeline. Filter for amountCheck: "converted" before calculating totals from it. Audit the BSON types on your own collection first if you need to limit which source types qualify for conversion.

See how to audit stored BSON types or how to validate future writes.