How does MongoDB handle schema validation?
Learn how MongoDB enforces schema validation with $jsonSchema, validationLevel and validationAction, plus how to add rules to existing collections via collMod.
Expected Interview Answer
MongoDB is schema-flexible but supports optional schema validation defined per collection, most commonly using a $jsonSchema validator that enforces required fields, data types, value ranges, and allowed properties on insert and update. You attach a validator when creating a collection or via collMod, and MongoDB checks documents against it before writing.
Validation behavior is controlled by two settings: validationLevel (strict checks all inserts and updates; moderate only checks documents that already satisfied the rules) and validationAction (error rejects invalid writes; warn logs them but allows the write). Besides $jsonSchema you can use standard query-operator expressions or $expr for cross-field rules. This lets teams start flexible and progressively enforce structure as the data model stabilizes.
- Enforces required fields and correct BSON types
- Constrains value ranges and allowed enums
- Configurable strictness via validationLevel
- Non-breaking rollout via validationAction: warn
- Keeps documents consistent without an external schema layer
AI Mentor Explanation
Schema validation is the match official checking each player's kit and registration before they take the field: bat size within limits, jersey number present, name on the team sheet. Set the umpire to strict and every entrant is inspected; set it to warn and irregularities are noted but play continues. MongoDB does the same, vetting each document against the rules before it enters the collection.
Step-by-Step Explanation
Step 1
Define the rules
Write a $jsonSchema listing required fields, bsonType for each, and constraints like minimum, maximum, or enum.
Step 2
Attach it to the collection
Use db.createCollection('users', { validator: { $jsonSchema: {...} } }) or add it later with collMod.
Step 3
Set validationLevel
strict checks all inserts and updates; moderate only re-checks documents that already conformed.
Step 4
Set validationAction
error rejects invalid writes; warn allows them but logs a warning — useful for a safe rollout.
Step 5
Test with valid and invalid docs
Insert conforming and non-conforming documents to confirm the validator rejects or warns as configured.
What Interviewer Expects
- Knowing MongoDB is flexible but supports optional validation
- Naming $jsonSchema as the primary mechanism
- Explaining validationLevel (strict vs moderate)
- Explaining validationAction (error vs warn)
- How to add validation to an existing collection via collMod
Common Mistakes
- Claiming MongoDB has no schema enforcement at all
- Confusing validationLevel with validationAction
- Forgetting that moderate skips previously non-conforming documents
- Using JSON type names instead of bsonType
- Assuming validation applies retroactively to existing data
Best Answer (HR Friendly)
“MongoDB lets each collection carry an optional rulebook that checks new records for required fields and correct types before saving them. You can make it strict and reject bad data, or lenient and just log warnings, so teams can tighten structure gradually as their data model matures.”
Code Example
db.createCollection('users', {
validator: {
$jsonSchema: {
bsonType: 'object',
required: ['email', 'age'],
properties: {
email: {
bsonType: 'string',
pattern: '^.+@.+$',
description: 'must be a valid email string and is required'
},
age: {
bsonType: 'int',
minimum: 0,
maximum: 120,
description: 'must be an integer between 0 and 120'
},
role: {
enum: ['admin', 'user', 'guest'],
description: 'must be one of the allowed roles'
}
}
}
},
validationLevel: 'strict',
validationAction: 'error'
})
// Add validation to an existing collection later
db.runCommand({
collMod: 'users',
validator: { $jsonSchema: { bsonType: 'object', required: ['email'] } },
validationAction: 'warn'
})Follow-up Questions
- What is the difference between validationLevel strict and moderate?
- How does validationAction warn help roll out validation safely?
- Why must you use bsonType instead of JSON type names?
- Does adding a validator affect documents already in the collection?
- How would you enforce a cross-field rule using $expr?
MCQ Practice
1. Which validationLevel checks ALL inserts and updates against the validator?
strict validates every insert and update. moderate only re-validates documents that already satisfied the rules, skipping previously non-conforming ones.
2. What does validationAction: 'warn' do for an invalid write?
warn permits the write to succeed while logging a warning, which is useful for observing violations during a gradual rollout before switching to error.
3. Which is the primary way to enforce document structure in MongoDB?
MongoDB uses $jsonSchema validators (with query-operator or $expr rules as alternatives). It has no foreign keys, triggers, or fixed columns like a relational database.
Flash Cards
How does MongoDB enforce a schema? — Via an optional per-collection validator, usually $jsonSchema, checked on insert and update.
validationLevel: strict vs moderate? — strict checks all writes; moderate only re-checks documents that already conformed to the rules.
validationAction: error vs warn? — error rejects invalid writes; warn allows them but logs a warning for safe rollout.
How to add validation to an existing collection? — Use the collMod command with a validator (and optional validationLevel/validationAction).
Does validation apply retroactively? — No. It only affects new writes; existing documents are not re-checked unless updated (subject to validationLevel).