Schema Validation
Enforce structure and data types on a collection using MongoDB's JSON Schema validation rules.
Why Add Validation to a Flexible-Schema Database?
MongoDB's flexibility is a feature, not an excuse to skip data integrity entirely. Schema validation lets you enforce required fields, correct types, and value constraints at the database level — a safety net that catches malformed documents even if application-level validation has a bug.
Defining a Validator
A validator is defined using JSON Schema syntax, passed when creating a collection.
db.createCollection("users", { validator: { $jsonSchema: { bsonType: "object", required: ["name", "email"], properties: { name: { bsonType: "string", description: "must be a string and is required" }, email: { bsonType: "string", pattern: "^.+@.+$", description: "must be a valid email" }, age: { bsonType: "int", minimum: 0, maximum: 150 }, }, }, },});Attempting to insert a document that violates this schema is rejected with a clear validation error.
Validation Levels
The validationLevel and validationAction options control how strictly and how loudly validation is enforced.
| Option | Values | Meaning |
|---|---|---|
| validationLevel | strict (default) / moderate | strict validates all inserts and updates; moderate only validates documents that already passed validation before |
| validationAction | error (default) / warn | error rejects invalid writes; warn logs a warning but allows the write through |
Setting validationAction: "warn" temporarily lets you introduce a new schema without breaking existing writes, while surfacing which documents don't yet conform — useful for a gradual migration.
Adding Validation to an Existing Collection
A validator can be added or changed on an already-existing collection with collMod, without needing to recreate it.
db.runCommand({ collMod: "users", validator: { $jsonSchema: { /* ... */ } }, validationLevel: "moderate",});FAQs
No — it's a complementary safety net at the database layer; application-level validation still matters for things like showing helpful error messages to a user before a request even reaches the database.
The overhead is generally small and well worth the data integrity guarantee it provides, though very complex schemas can add measurable cost — profile if you have concerns at extreme write volumes.
Summary
JSON Schema validation lets you enforce structure and types even in a flexible-schema database, with tunable strictness for migrations. With schema design covered, the next section moves into indexes — the key to making all of this fast at scale.