Collection validators
coreintermediateA 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.
Think of it as
A collection without a validator accepts any document shape — flexibility with no safety net. A validator adds the safety net without removing the flexibility everywhere else: it can require some fields and constrain some types while leaving anything not mentioned free to vary, unlike a relational table's fixed column list.
What we're doing: Show a validator rejecting an insert that violates it, and one that is allowed because the field it violates is not covered.
- 2
- The validator enforces total >= 0 because that field is explicitly constrained — the insert is rejected before it is written.
- 6
- The "notes" field is not mentioned anywhere in the validator, so it passes through unconstrained — this is what "partial" validation means in practice.
Why this works: A validator lets a team lock down the fields that matter for correctness (an order must have a non-negative total) while leaving room for fields that genuinely vary or are still evolving — the two are not mutually exclusive in the same collection.
Assuming a validator with a few required fields makes the whole document schema-safe
Wrong
Better
What you see: A malformed value lands in a field the team assumed was covered, because the validator never actually mentioned it.
Why: A collection validator only checks what it explicitly lists — omission is not an oversight the database catches for you, it is the schema-flexible default applying to anything the validator does not name.
- orders collection
- customerId, total — required, type-checked
- everything else — still schema-flexible
Attaching a validator
Together
Remember: 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.
See also: json schema validation · schema flexible not free

