Working with Data
Validation Rules
Configure document validation rules for collections
Validation Rules
BusinessConfigure JSON Schema validation rules to enforce data integrity and consistency.
Overview
MongoDB validation rules ensure documents match a defined schema before being inserted or updated.
Creating Validation Rules
Schema Format
Use JSON Schema to define validation:
{
"$jsonSchema": {
"bsonType": "object",
"required": ["email", "name"],
"properties": {
"email": {
"bsonType": "string",
"pattern": "^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\\.[a-zA-Z]{2,}$",
"description": "Valid email address required"
},
"name": {
"bsonType": "string",
"minLength": 1,
"maxLength": 100
},
"age": {
"bsonType": "int",
"minimum": 0,
"maximum": 120,
"description": "Age in years"
},
"status": {
"enum": ["active", "inactive", "pending"],
"description": "Account status"
}
}
}
}
Validation Levels
Strict
Rejects any document that doesn't match the schema.
Use when:
- Starting a new collection
- Data quality is critical
- All applications follow the schema
Moderate
Warns about invalid documents but allows insertion.
Use when:
- Migrating existing collections
- Gradual schema enforcement
- Some flexibility needed
Strict validation prevents any writes that violate the schema. Test thoroughly before enabling.
Common Validation Patterns
Required Fields
{
"required": ["email", "name", "createdAt"]
}
Type Constraints
{
"properties": {
"age": { "bsonType": "int" },
"email": { "bsonType": "string" },
"active": { "bsonType": "bool" }
}
}
Enum Values
{
"status": {
"enum": ["draft", "published", "archived"]
}
}
Nested Objects
{
"address": {
"bsonType": "object",
"required": ["city", "country"],
"properties": {
"city": { "bsonType": "string" },
"country": { "bsonType": "string" },
"postalCode": { "bsonType": "string" }
}
}
}
Testing Validation
Before applying validation:
- Test with sample documents
- Check existing documents for compliance
- Fix invalid documents
- Enable validation
Monitoring Validation
View validation errors:
- Failed insert/update attempts
- Error messages and reasons
- Affected documents