Schema Validation on Collections — MongoDB Technical Interview Questions & Answers
Optional $jsonSchema rules for document shape.
Schema Validation on Collections
- Simple meaning: You can attach a JSON Schema so inserts must have name, roll, etc. Optional — Mongo is still flexible by default.
- How to use: db.createCollection("students", { validator: { $jsonSchema: { required: ["name", "roll"], properties: { roll: { bsonType: "int" } } } } }).
- Try this: validator on, then insert without roll — it should fail.
- Common mistake: thinking Mongo always validates like SQL NOT NULL. Default is off.
- Interview tip: Optional $jsonSchema. Default = schemaless. Validation is per collection.
Technical Interview Tip: Validation is opt-in, not default SQL-strict.
Code Examples for Schema Validation on Collections
Schema Validation on Collections — working example
db.runCommand({
collMod: "users",
validator: {
$jsonSchema: {
bsonType: "object",
required: ["email", "name"],
properties: {
email: { bsonType: "string", pattern: "^.+@.+\..+$" },
name: { bsonType: "string", minLength: 1 }
}
}
},
validationLevel: "moderate"
})Schema Validation on Collections — $jsonSchema validators enforce document shape on inserts/updates.
How to Explain Schema Validation on Collections to an Interviewer
Does MongoDB require a schema?
No by default You can add $jsonSchema validators