MongoDB โ Schema Validation & JSON Schema
Enforce database-level validation rules using JSON Schema ($jsonSchema) and collMod commands.
1Enforcing Schema Rules with $jsonSchema
createCollection with Validation
db.createCollection("users", {
validator: {
$jsonSchema: {
bsonType: "object",
required: ["name", "email", "age"],
properties: {
name: { bsonType: "string", description: "Must be a string" },
email: { pattern: "^.+@.+$", description: "Must be a valid email" },
age: { bsonType: "int", minimum: 18, description: "Must be an integer >= 18" }
}
}
},
validationAction: "error"
});
2Modifying Validation Rules on Existing Collections
collMod Command Example
// Modify validation rules without recreating collection
db.runCommand({
collMod: "users",
validator: {
$jsonSchema: {
bsonType: "object",
required: ["name", "email", "status"]
}
},
validationLevel: "moderate"
});