1.Collection validators
A collection validator is a set of rules, attached to a collection, that MongoDB checks against every insert and (depending on settings) every update. It is the database enforcing structure on an otherwise schema-flexible collection, not a replacement for it.
Key features
- A validator is set via createCollection's validator option, or added later with collMod
- It runs on insert always, and on update depending on validationLevel
- Rules are commonly written as $jsonSchema — required fields, bsonType, ranges, patterns
- A validator can be partial: it only constrains the fields it mentions, others stay unconstrained
- Validation failures are reported per operation, not silently ignored
Attaching a validator
- orders collection
- customerId, total — required, type-checked
- everything else — still schema-flexible
Command
db.createCollection(<name>, { validator: { $jsonSchema: {...} }, validationLevel: <level>, validationAction: <action> })A collection validator enforces structure only on the fields it explicitly lists — attach with createCollection or collMod, and check existing data before switching to strict.