Optional Structure
Document databases are schema flexible by default, but unlimited flexibility can let bad data creep in. MongoDB lets you attach schema validation to a collection so writes must satisfy declared rules.
Defining Rules
Validation is expressed with a JSON Schema style document that can require fields, fix their types, and constrain values.
- Require that an email field exists and is a string.
- Restrict a status field to a fixed set of allowed values.
- Set minimum and maximum bounds on numeric fields.
Validation Levels and Actions
- The level controls whether rules apply to all writes or only to documents that already passed.
- The action chooses whether a violating write is rejected with an error or merely logged as a warning.
This lets teams tighten a schema gradually. Start with warnings to find offenders, then switch to error mode once existing data conforms. Validation runs on inserts and updates, not on existing documents until they are next written.
Key idea
Schema validation adds optional JSON Schema rules to a collection so writes must satisfy required fields, types, and value bounds, with levels and actions that let teams tighten structure gradually.