MongoDB Schema Validation
MongoDB lets each document in a collection carry different fields. That freedom helps during early development and causes trouble later when one document stores a price as a number and another stores it as text. Schema validation adds rules that every new or changed document must follow. The database rejects anything that breaks a rule.
The Security Gate Picture
Think of a security gate at a building entrance. The guard checks each visitor for a valid pass before opening the door. Schema validation plays the guard for your collection.
New document
|
v
+------------------+
| Validation |
| rules (gate) |
+------------------+
| |
passes fails
| |
v v
Saved in Rejected with
collection error code 121Create a Collection with Rules
MongoDB uses the $jsonSchema operator to describe the rules. The example below builds a students collection:
db.createCollection("students", {
validator: {
$jsonSchema: {
bsonType: "object",
required: ["name", "age", "email"],
properties: {
name: {
bsonType: "string",
description: "Name must be text"
},
age: {
bsonType: "int",
minimum: 5,
maximum: 100,
description: "Age must be a whole number from 5 to 100"
},
email: {
bsonType: "string",
pattern: "^.+@.+\\..+$",
description: "Email must look like name@site.com"
},
grade: {
enum: ["A", "B", "C", "D"],
description: "Grade must be one of the listed letters"
}
}
}
}
})Rule Keywords Explained
| Keyword | Purpose |
|---|---|
| bsonType | Sets the required data type |
| required | Lists fields that every document must include |
| properties | Holds the rules for individual fields |
| minimum / maximum | Sets the lowest and highest number allowed |
| minLength / maxLength | Sets the shortest and longest text allowed |
| pattern | Requires text to match a regular expression |
| enum | Allows only the listed values |
| description | Explains the rule in plain words |
Test the Rules
A Valid Document
db.students.insertOne({ name: "Asha", age: NumberInt(14), email: "asha@example.com", grade: "A" })MongoDB accepts this document because every rule passes. The NumberInt helper makes sure the age is stored as a whole number type.
An Invalid Document
db.students.insertOne({ name: "Rohit", age: NumberInt(3), email: "rohit-at-example" })MongoDB rejects this document with the message Document failed validation. The age falls below the minimum of 5, and the email does not match the pattern.
Control the Strictness
Two settings decide how firmly MongoDB applies the rules.
validationAction
- error blocks the write and returns an error. This is the default.
- warn allows the write and records a warning in the server log.
validationLevel
- strict checks every insert and every update. This is the default.
- moderate checks inserts and updates only on documents that already satisfy the rules. Older invalid documents stay editable.
db.runCommand({
collMod: "students",
validationAction: "warn",
validationLevel: "moderate"
})The warn and moderate combination suits a collection that already holds messy data. The team can fix old documents step by step while new data stays clean.
Add Rules to an Existing Collection
The collMod command attaches or changes rules on a collection that already exists:
db.runCommand({
collMod: "products",
validator: {
$jsonSchema: {
bsonType: "object",
required: ["name", "price"],
properties: {
name: { bsonType: "string" },
price: { bsonType: "double", minimum: 0 }
}
}
},
validationLevel: "moderate"
})Existing documents stay untouched. MongoDB applies the new rules only to later writes.
Check the Current Rules
db.getCollectionInfos({ name: "students" })The output shows the validator in the options section.
Nested Documents and Arrays
Rules can describe objects inside objects and items inside arrays:
properties: {
address: {
bsonType: "object",
required: ["city"],
properties: { city: { bsonType: "string" } }
},
subjects: {
bsonType: "array",
minItems: 1,
items: { bsonType: "string" }
}
}This rule requires a city inside the address and a subjects list with at least one text item.
Good Practices
- Start with the few fields that matter most, such as required identifiers and prices.
- Write a clear
descriptionfor each rule so teammates understand the intent. - Test the rules on a copy of the collection before using them in production.
- Pair validation with application checks. The database acts as the last safety net.
Summary
Schema validation keeps a flexible database tidy. The $jsonSchema operator describes required fields, data types, ranges, patterns, and allowed values. The validationAction and validationLevel settings control how strictly MongoDB enforces those rules. The collMod command adds validation to collections that already exist. A small set of well-chosen rules prevents most data quality problems.
