collMod with validator enforces JSON Schema rules on insert/update—middle ground between rigid SQL and no rules.
Create validator
db.createCollection('invoices', {
validator: {
$jsonSchema: {
bsonType: 'object',
required: ['customerId', 'total', 'issuedAt'],
properties: {
customerId: { bsonType: 'string' },
total: { bsonType: ['int', 'double', 'decimal'] },
issuedAt: { bsonType: 'date' }
}
}
},
validationLevel: 'moderate'
})Practice: Run on practice in mongosh.
validationAction
error rejects bad writes; warn logs in older patterns—prefer error in production.
Important interview questions and answers
- Q: Validator vs app-only checks?
A: DB-side validation blocks rogue scripts and ad-hoc shells. - Q: moderate vs strict?
A: moderate validates updates only if they touch validated fields.
Self-check
- What does $jsonSchema enforce?
- Name three required invoice fields in the example.
Tip: Validators catch bad writes from shells and legacy scripts—not only app code.
Interview prep
- $jsonSchema?
- Declares required fields and BSON types on writes.
- validationLevel moderate?
- Validates updates touching validated fields.