MongoDB Schema Validation

Validating document structure

Create with Validation

db.createCollection('users', {
    validator: {
        $jsonSchema: {
            bsonType: 'object',
            required: ['name', 'email'],
            properties: {
                name: {
                    bsonType: 'string',
                    description: 'must be a string'
                },
                age: {
                    bsonType: 'int',
                    minimum: 0
                }
            }
        }
    }
})

Add Validation

db.runCommand({
    collMod: 'users',
    validator: {
        $jsonSchema: { /* schema */ }
    },
    validationLevel: 'strict'
})

Validation Levels

'strict' # all inserts and updates
'moderate' # existing valid documents only

Validation Actions

'error' # reject invalid documents
'warn' # allow but log warning