MongoDB — Validation
Basic Validation
db.createCollection("users", {
validator: {
$jsonSchema: {
bsonType: "object",
required: ["name", "email"],
properties: {
name: {
bsonType: "string",
description: "Must be a string"
},
email: {
bsonType: "string",
pattern: "^.+@.+$",
description: "Must be valid email"
},
age: {
bsonType: "int",
minimum: 0,
maximum: 150
}
}
}
}
})
Validation Levels
| Level | Description |
|---|---|
| strict | Reject invalid docs |
| moderate | Allow updates to existing |
db.runCommand({
collMod: "users",
validationLevel: "moderate"
})
Validation Actions
| Action | Description |
|---|---|
| error | Reject invalid |
| warn | Log warning |
db.runCommand({
collMod: "users",
validationAction: "warn"
})
Add Validation
db.runCommand({
collMod: "users",
validator: { ... }
})
Mini Practice
- Add validation rules
- Test validation
- Change validation level
- Remove validation
Up Next
Continue with Security — MongoDB security.
Related Topics
Frequently Asked Questions about Validation
What is Validation in MongoDB?
Validation is a fundamental concept in MongoDB. This lesson explains it step by step with clear examples, making it easy for beginners to understand.
How do I learn Validation?
Start by reading the explanation above, then try the code examples. Practice by modifying the examples and experimenting with different values. Hands-on practice is the best way to learn Validation.
Why is Validation important in MongoDB?
Validation is essential for MongoDB development. Understanding this concept will help you write better code and solve real-world problems more effectively.