Filter concepts by levelShowing all levels.

MongoDB · Schema Validation

Schema Validation

Collection validators, $jsonSchema, validation levels/actions, and the app-side validation gap

  • Validators are partialonly the fields they name are constrained
  • $jsonSchema uses bsonTypenot plain JSON Schema's type
  • strict vs. moderatemoderate spares already-invalid documents
  • A backstop, not a redundancycovers write paths app validation never sees

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

Attaching a validator
WhenHow
New collectiondb.createCollection(name, { validator: {...} })
Existing collectiondb.runCommand({ collMod: name, validator: {...} })
Remove validationdb.runCommand({ collMod: name, validator: {}, validationLevel: "off" })
A validator is a partial rule set, not a fixed schema

orders collection

customerId, total

required, type-checked

everything else

still schema-flexible

  • orders collection
    • customerId, total — required, type-checked
    • everything else — still schema-flexible

Command

text
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.

2.JSON Schema validation concepts

$jsonSchema is the standard, richest way to write a validator: required lists which fields must exist, properties describes each field's bsonType and constraints (minimum, maximum, pattern, enum), and schemas can nest for embedded documents and arrays.

Key features

  • required: array of field names that must exist on the document
  • properties: an object mapping each field name to its own constraint (bsonType, minimum/maximum, pattern, enum)
  • bsonType (not type): uses BSON type names like "string", "decimal", "objectId", not plain JSON types
  • Nested objects and arrays can each carry their own properties/items schema, for deep validation
  • additionalProperties: false can forbid fields not listed in properties, if that strictness is wanted

Command

text
{ bsonType: "object", required: [...], properties: { <field>: { bsonType: ..., ... } } }

$jsonSchema: required lists mandatory fields, properties constrains each one by bsonType (not type) — nests the same way for embedded documents and arrays.

3.Using validation for structural and type guarantees

Reach for a validator on the fields where a wrong type or a missing value would break something downstream — a total that must be a number, a status that must be one of a fixed set, an id that must reference a real type. Not every field needs this level of guarantee.

Key features

  • Validate fields that other code depends on having a specific type or one of a fixed set of values
  • A missing or wrong-typed required field is a common source of downstream bugs that validation catches at write time
  • Validation is cheaper to enforce at write time than to detect later via a data-quality audit
  • Over-validating (locking down fields nothing depends on) adds friction without a matching guarantee benefit
  • Validation complements, but does not replace, correct application logic — see the application-side mistake below

Command

text
// Ask per field: "if this is missing or the wrong type, what breaks downstream?" — validate exactly those

Validate the fields other code actually depends on having a specific shape — a wrong type there breaks something downstream. Leave genuinely variable or display-only fields unconstrained.

4.validationLevel and validationAction

validationLevel controls which writes get checked: strict (every insert and update) or moderate (inserts, plus updates only to documents already valid — existing invalid documents are left alone). validationAction controls what happens on failure: error (reject) or warn (allow, but log).

Key features

  • validationLevel: "strict" (default) checks every insert and update, including updates to already-invalid documents
  • validationLevel: "moderate" checks inserts and updates to already-valid documents; leaves already-invalid documents alone
  • validationAction: "error" (default) rejects a failing write outright
  • validationAction: "warn" allows a failing write through, but logs the violation
  • validationLevel: "off" disables validation entirely without removing the validator definition

Level × action, and when each combination fits

Level × action, and when each combination fits
LevelActionFits
stricterrora stable schema with no legacy non-conforming documents
strictwarntesting a new rule's real-world impact before enforcing it
moderateerrorenforcing new rules going forward, without breaking updates to legacy documents
moderatewarnrolling out a validator gradually on a collection with a lot of legacy data
Level × action — four real combinations
moderate + warn
gradual rollout on legacy data
moderate + error
enforce new rules, spare legacy docs
strict + warn
test a new rule's real impact
strict + error
full enforcement, stable schema
  • moderate + warn: action: warn, level: moderate — gradual rollout on legacy data
  • moderate + error: action: error, level: moderate — enforce new rules, spare legacy docs
  • strict + warn: action: warn, level: strict — test a new rule's real impact
  • strict + error: action: error, level: strict — full enforcement, stable schema

Command

text
{ validationLevel: "strict" | "moderate" | "off", validationAction: "error" | "warn" }

validationLevel picks which writes get checked (strict = all, moderate = spares already-invalid documents); validationAction picks what happens on failure (error = reject, warn = log only). Roll out new validators as moderate/warn first.

5.Balancing flexible evolution with strong validation

Not every collection needs the same validation strength. Business-critical data (payments, orders, inventory) benefits from strict validation; fast-evolving or exploratory data (feature flags, event payloads, logs) benefits more from staying flexible while the shape is still settling.

Key features

  • Critical collections (payments, inventory, orders) justify strict validation — a bad document there is expensive
  • Fast-evolving collections (new features, event payloads still being designed) justify staying loose longer
  • The same project reasonably has both kinds of collections, each validated differently
  • A collection can move from loose to strict over time, once its shape has stabilized
  • Over-validating an evolving collection creates friction that slows down legitimate schema iteration

Command

text
// Per collection: how costly is a bad document here, versus how much is the shape still expected to change?

Set validation strength per collection: strict for critical, stable data (payments, orders); loose for fast-evolving, exploratory data — and tighten it once a collection's shape settles.

6.Application validation is not the only protection

Application code that validates before writing is easy to bypass: a second service, a one-off script, a bulk import, or a bug in that same code path can all write directly to the collection without going through the validation logic. A collection validator checks every write, regardless of where it came from.

Key features

  • Application validation only runs for writes that go through that specific code path
  • A second service, a script, or a bug can write to the same collection bypassing that path entirely
  • A collection validator runs at the database, so it applies no matter which code produced the write
  • The two are complementary, not redundant: app validation gives good error messages early; the validator is the backstop that always runs
  • A collection with only application-side validation has exactly as many gaps as it has write paths that skip that validation
Every write path, one shared backstop

App API writes

validated by application code

Migration scripts

bypass the app entirely

Other services

their own write paths, own bugs

Collection validator

runs at the database — every path above hits it

  1. App API writes — validated by application code
  2. Migration scripts — bypass the app entirely
  3. Other services — their own write paths, own bugs
  4. Collection validator — runs at the database — every path above hits it

Command

text
// App-side validation: fast feedback, one code path. Database validator: no bypass, every code path.

Application validation only covers the code paths that use it — a collection validator runs at the database and catches every write path, including ones added later. Use both, not one instead of the other.

Remember

  • A validator only constrains the fields it explicitly lists — everything else stays schema-flexible.
  • $jsonSchema uses bsonType (BSON-aware), not JSON Schema's plain type keyword.
  • validationLevel picks which writes get checked; validationAction picks error vs. warn on failure.
  • A collection validator is the backstop for write paths — scripts, other services — that skip app-side checks.

Pro tip

  • Roll out a new validator as moderate + warn first, fix what the logs surface, then tighten to strict + error.
  • Set validation strength per collection — strict for critical, stable data; loose for still-evolving shapes.

Next up

  • Indexing Fundamentals
  • Compound Index Design
  • Query Planning

Sources

  • Schema validation — mongodb.com/docs/manual/core/schema-validation/
  • Specify JSON Schema validation — mongodb.com/docs/manual/core/schema-validation/specify-json-schema/
  • Checked 2026-08-21

Spotted a mistake on this page? Tell us.