Lesson 3 of 9 · 21m
Validation, Evolution, and Migration Without Drama
How to keep flexible documents honest with `$jsonSchema`, evolve shapes safely, and migrate production data without taking the system down.
MongoDB's flexibility is valuable because schemas evolve, not because chaos is a feature. The successful deployments I've seen treat document shape as a contract. They validate at the database where cheap, validate in the application where semantics matter, and migrate data in small observable steps.
$jsonSchema is a guardrail, not a specification language
db.createCollection("users", {
validator: {
$jsonSchema: {
bsonType: "object",
required: ["email", "displayName", "createdAt"],
properties: {
email: { bsonType: "string", pattern: "^[^@\\s]+@[^@\\s]+\\.[^@\\s]+$" },
displayName: { bsonType: "string", minLength: 1, maxLength: 80 },
roles: { bsonType: "array", items: { enum: ["member", "support", "billing-admin", "admin"] } },
createdAt: { bsonType: "date" }
}
}
},
validationLevel: "strict",
validationAction: "error"
})Use database validation to reject structurally impossible data: missing required fields, wrong BSON types, impossible enums. Do not try to encode every business invariant there. "A trial account cannot also be suspended" belongs in application logic or a transaction.
Evolve by expansion, then contraction
The safe pattern is expand, migrate, contract:
- Deploy code that writes both
nameanddisplayName, readingdisplayNamewith a fallback. - Backfill old documents in batches.
- Deploy code that reads only
displayName. - Later, remove writes of the old field and optionally clean it up.
db.users.updateMany({ displayName: { $exists: false }, name: { $type: "string" } }, [{ $set: { displayName: "$name" } }], { writeConcern: { w: "majority" } })Pipeline-style updates avoid reading every document into the application just to copy a field. Still batch enormous backfills so you can observe replication lag, memory, and lock behavior.
Make migrations boring
A production migration should have a written shape:
- selector: which documents are old?
- batch size: often 500-5000, tuned by document size
- progress marker: collection scan order or last
_id - rollback or forward-fix plan
- verification query: count documents that still fail the new invariant
Do not assume zero downtime means zero behavioral change. During migration, both shapes exist. Reads must tolerate both or be versioned explicitly with a schemaVersion field.
Field notes
validationAction: "warn"is useful for observation, but warnings nobody dashboards are just expensive logging.- Add
schemaVersionwhen shape migration will span multiple deployments. Future-you will be grateful. - Never backfill in one giant
updateManyon a live primary because the syntax is convenient. Batch and measure. - Type drift is the silent killer:
qty: 2andqty: "2"can coexist until a sort or comparison starts behaving like a haunted house.
Was this lesson helpful?