KeplerGrid guide

Audit MongoDB field types with $type and $group

Before adding validation, count how many documents store a field as each BSON type. Use aggregation $type to distinguish missing from null and to identify an array as an array.

Count the stored types in an aggregation

Load the eight synthetic cases and open keplergrid_filter_lab.cases with a Read only connection. In KeplerGrid select Aggregation → JSON, paste this pipeline, and select Run pipeline.

[
  { "$group": {
    "_id": { "$type": "$slaHours" },
    "documents": { "$sum": 1 }
  } },
  { "$sort": { "_id": 1 } }
]

Expect two documents in the int group and one in each of array, bool, decimal, missing, null, and string. Together the seven rows account for eight cases. CASE-105 is missing the field, while CASE-104 stores an explicit null.

Look up the documents behind an unexpected type

In Documents, paste this into Filter to compare the type of the whole field to string. Choose Run and switch to JSON view to inspect the result.

{
  "$expr": {
    "$eq": [{ "$type": "$slaHours" }, "string"]
  }
}

CASE-102 stores "12" as a string. CASE-106 stays in the array group even though its array contains an integer. The aggregation expression checks the whole value, whereas the query $type operator can also match an array element.

Review the counts before validation

Decide which types are meaningful for the field, then inspect representative documents before changing data or validation rules. If you add a $match before $group, the counts describe only that matched subset.

See how to check null and missing with filters and how to test a schema validator on a practice collection.

After auditing the stored values, convert field types in an aggregation and inspect errors before changing data.