A MongoDB collection events is written by three versions of a mobile app and loaded nightly into a typed warehouse table. Old versions send price as a string ("199.00"), new ones as a number, and some events omit it; the nested device object keeps gaining fields. Last week the load failed when price arrived as a string, and the hotfix cast every column to text, which broke the revenue reports. MongoDB has no schema validation on the collection. Constraints: analysts need typed columns, a bad document must not stop the whole load, any day may need to be reloaded, and the app team can change its payload with a week's notice. Design how documents land in the warehouse so that new fields and type changes neither break the load nor silently corrupt reports.
Land each document unchanged as JSON in a raw layer with its load date, so any day can be reloaded. In staging, cast known fields explicitly, send rows that fail to quarantine with an alert, keep new fields in JSON. Add a contract or $jsonSchema at the source.
- Casting every column to text so the load never fails, which moves the failure into every report
- Dropping documents that do not fit the table instead of quarantining them for a fix and a reload
- Keeping no raw copy, so a fixed cast cannot be re-applied to the days already loaded
- How would you detect a new field in
devicebefore an analyst asks for it? - What would a MongoDB
$jsonSchemavalidator withvalidationAction: warngive you, compared witherror?
Layers.
- Raw layer (schema-on-read). Each whole document: a JSON column (
VARIANTin Snowflake,JSONin BigQuery,jsonbin PostgreSQL),_id, load date, app version. Nothing is cast or dropped; reloading a day means rebuilding staging from this layer. - Staging (schema-on-write). Explicit casts of the known fields, with a rule for each variant:
SELECT
doc->>'_id' AS event_id,
CASE jsonb_typeof(doc->'price')
WHEN 'number' THEN (doc->>'price')::numeric
WHEN 'string' THEN CASE WHEN doc->>'price' ~ '^[0-9]+(\.[0-9]+)?$'
THEN (doc->>'price')::numeric END -- old app versions
END AS price,
doc->'device' AS device_raw -- new fields stay in JSON
FROM raw.events
WHERE load_date = :day;Rows where the document has a price that could not be cast ('199,00', 'free') go to a quarantine table with the reason instead of failing the load; an alert fires on their share. 3. Marts read only staging; new fields in device_raw become columns on request, by rebuilding staging from the raw layer.
The source. The week's notice becomes a contract: a list of fields and types, checked in the app's CI or by a $jsonSchema validator on the collection. warn logs violations without blocking the app — a sensible first step; error rejects the write.
Until the collection has a validator, the source enforces no schema, so the raw document layer does the main work, not the agreement alone.