Schema Validation Rules
Introduction to Schema Validation
MongoDB provides a powerful mechanism to enforce document structure and data integrity through schema validation rules. These rules allow developers to define specific constraints on document fields, ensuring data quality and consistency.
Validation Levels and Modes
graph TD
A[Validation Strategies] --> B[Validation Level]
A --> C[Validation Action]
B --> D[strict: Validate all inserts/updates]
B --> E[moderate: Validate only new documents]
C --> F[error: Reject invalid documents]
C --> G[warn: Log validation warnings]
Creating Validation Rules
Basic Validation Example
## Create a collection with validation rules
db.createCollection("users", {
validator: {
$jsonSchema: {
bsonType: "object",
required: ["username", "email", "age"],
properties: {
username: {
bsonType: "string",
description: "Username must be a string"
},
email: {
bsonType: "string",
pattern: "^.+@.+$",
description: "Must be a valid email"
},
age: {
bsonType: "int",
minimum: 18,
maximum: 100,
description: "Age must be between 18 and 100"
}
}
}
},
validationLevel: "strict",
validationAction: "error"
})
Validation Operators
Operator |
Description |
Example |
$jsonSchema |
Comprehensive JSON schema validation |
Validate document structure |
$type |
Check field data type |
Ensure field is a specific type |
$exists |
Verify field presence |
Require or prohibit fields |
$regex |
Validate string patterns |
Check email or username format |
Advanced Validation Scenarios
Complex Nested Document Validation
db.createCollection("products", {
validator: {
$jsonSchema: {
bsonType: "object",
required: ["name", "price", "category"],
properties: {
name: {
bsonType: "string",
minLength: 2,
maxLength: 50
},
price: {
bsonType: "double",
minimum: 0
},
category: {
enum: ["electronics", "clothing", "books"]
},
specifications: {
bsonType: "object",
properties: {
weight: {
bsonType: "double",
minimum: 0
}
}
}
}
}
}
})
Validation Best Practices
- Define clear and precise validation rules
- Use appropriate validation levels
- Provide meaningful error descriptions
- Balance between flexibility and data integrity
- Test validation rules thoroughly
Common Validation Challenges
- Performance overhead
- Complexity of nested schemas
- Balancing strict rules with application needs
LabEx Recommendation
When working with schema validation in LabEx environments, always consider:
- Your specific use case
- Performance implications
- Future schema evolution
By implementing robust schema validation, you can significantly improve data quality and maintain consistency in your MongoDB databases.