Evolving Schemas Without Downtime
Learners will update an existing validator on a live collection and write migration scripts to backfill documents to the new shape.
The Challenge of Schema Evolution
As your application grows, requirements change and your MongoDB schema must evolve. Unlike relational databases, you cannot run a blocking ALTER TABLE that locks the entire table during migration. MongoDB's flexibility means old and new document shapes can coexist in the same collection, which requires a deliberate migration strategy to keep the application working while the schema transitions.
Step 1: Update the Validator in Warn Mode
Begin every schema migration by updating the collection's validator to reflect the new schema, but with validationAction: 'warn'. This allows existing non-conforming documents to remain and be updated without errors while you measure how many documents need to be backfilled. New writes from updated application code will conform to the new schema.
// Add a new required field 'phoneNumber' to the validator
db.runCommand({
collMod: 'users',
validator: {
$jsonSchema: {
bsonType: 'object',
required: ['name', 'email', 'phoneNumber'],
properties: {
name: { bsonType: 'string' },
email: { bsonType: 'string' },
phoneNumber: { bsonType: 'string' }
}
}
},
validationLevel: 'moderate',
validationAction: 'warn'
});All lessons in this course
- Adding a Validator to a Collection
- Type, Required, and Enum Constraints
- Validation Levels and Actions
- Evolving Schemas Without Downtime