MongoDB's flexible schema is a strength, but real applications usually still want some guarantees — a users collection where every document is required to have an email. Schema validation lets you enforce exactly the rules you choose, and no more.
db.createCollection("users", {
validator: {
$jsonSchema: {
bsonType: "object",
required: ["name", "email"],
properties: {
name: { bsonType: "string" },
email: { bsonType: "string", pattern: "^.+@.+$" },
age: { bsonType: "int", minimum: 0 }
}
}
}
})Trying to insert a document that breaks a required rule fails with a validation error instead of being saved:
db.users.insertOne({ name: "Test User" })
// Error: Document failed validation — "email" is requiredcollMod applies a validator to a collection that already exists:
db.runCommand({
collMod: "users",
validator: {
$jsonSchema: {
required: ["email"]
}
}
})Existing documents are not checked retroactively
By default, validation applies to new inserts and updates but does not retroactively check documents already in the collection — existing data that would fail the new rule stays exactly as it is unless it is updated or you set validationLevel: "strict".