MongoDB Schema Validation
A flexible schema is convenient, but it also means a bug can store price: '12' (a string) or forget name entirely. Schema validation lets the server check every insert and update against rules you define, so bad data never gets in.
Rules are attached to a collection with the validator option, usually written as a JSON Schema with the $jsonSchema operator.
Creating a collection with a validator
mongosh · try it yourself
db.createCollection('suppliers', {
validator: {
$jsonSchema: {
bsonType: 'object',
required: ['name', 'country', 'rating'],
properties: {
name: { bsonType: 'string', minLength: 2, description: 'supplier name' },
country: { enum: ['Brazil', 'Colombia', 'Ethiopia', 'India', 'Japan', 'Kenya'] },
rating: { bsonType: 'int', minimum: 1, maximum: 5 },
email: { bsonType: 'string', pattern: '^.+@.+