TExcelTAD
Home › MongoDB › MongoDB Schema Validation

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: '^.+@.+
  

 }
      }
    }
  }
});

db.suppliers.insertOne({ _id: 1, name: 'Sidamo Growers', country: 'Ethiopia', rating: NumberInt(5) });
print(db.suppliers.countDocuments(), 'valid supplier stored');
1 valid supplier stored

When a document fails

An invalid insert or update is rejected with error code 121, Document failed validation. The error's errInfo explains which rule failed:

mongosh · try it yourself
db.createCollection('suppliers', {
  validator: { $jsonSchema: {
    bsonType: 'object',
    required: ['name', 'country', 'rating'],
    properties: {
      name: { bsonType: 'string' },
      rating: { bsonType: 'int', minimum: 1, maximum: 5 }
    }
  } }
});

try {
  db.suppliers.insertOne({ _id: 2, name: 'Kyoto Leaf', rating: NumberInt(9) });
} catch (err) {
  print(err.code, err.message);
  for (const rule of err.errInfo.details.schemaRulesNotSatisfied) {
    print('-', rule.operatorName, JSON.stringify(rule.missingProperties ?? rule.propertiesNotSatisfied.map(p => p.propertyName)));
  }
}
121 Document failed validation
- properties ["rating"]
- required ["country"]

Two rules failed: the required property country is missing, and rating is out of range.

Common JSON Schema keywords

Keyword Checks
bsonType the BSON type: 'string', 'int', 'double', 'decimal', 'date', 'object', 'array', … (or an array of types)
required fields that must be present
properties rules for each field
enum allowed values
minimum / maximum number range
minLength / maxLength / pattern string length and regular expression
items, minItems, maxItems, uniqueItems array contents and length
additionalProperties: false forbid fields not listed in properties

Rules nest, so embedded documents and arrays of documents can be validated too:

mongosh · try it yourself
db.createCollection('carts', {
  validator: { $jsonSchema: {
    bsonType: 'object',
    required: ['customerId', 'items'],
    properties: {
      customerId: { bsonType: 'int' },
      items: {
        bsonType: 'array',
        minItems: 1,
        items: {
          bsonType: 'object',
          required: ['productId', 'qty'],
          properties: { productId: { bsonType: 'int' }, qty: { bsonType: 'int', minimum: 1 } }
        }
      }
    }
  } }
});

function tryInsert(doc) {
  try { db.carts.insertOne(doc); return 'ok'; } catch (err) { return 'rejected (' + err.code + ')'; }
}
print(tryInsert({ _id: 1, customerId: NumberInt(3), items: [{ productId: NumberInt(1), qty: NumberInt(2) }] }));
print(tryInsert({ _id: 2, customerId: NumberInt(3), items: [] }));
print(tryInsert({ _id: 3, customerId: NumberInt(3), items: [{ productId: NumberInt(1), qty: NumberInt(0) }] }));
ok
rejected (121)
rejected (121)

Note: A plain 3 typed in mongosh is a double, so bsonType: 'int' rejects it. Either write NumberInt(3) or allow both with bsonType: ['int', 'double'] (or the alias 'number').

Adding validation to an existing collection

collMod changes the validator of a collection that already holds data. Two options control what happens with existing and invalid documents:

Option Values
validationLevel 'strict' (default): check all inserts and updates; 'moderate': don't check updates to documents that were already invalid
validationAction 'error' (default): reject; 'warn': accept but write a warning to the server log
mongosh · try it yourself
db.runCommand({
  collMod: 'products',
  validator: { $jsonSchema: {
    required: ['name', 'price'],
    properties: { price: { bsonType: 'number', minimum: 0 } }
  } },
  validationLevel: 'strict'
});

try {
  db.products.updateOne({ _id: 1 }, { $set: { price: -5 } });
} catch (err) {
  print('update rejected:', err.code);
}
print(db.products.findOne({ _id: 1 }).price);
// Existing documents are not checked when the validator is added; find the ones that break it:
print(db.products.countDocuments({ $nor: [db.getCollectionInfos({ name: 'products' })[0].options.validator] }));
update rejected: 121
24.5
0

The last line uses the validator as a query to count documents that don't satisfy it: none here.

Test yourself

What error code does MongoDB return when a document fails validation?

  1. 11000
  2. 121
  3. 404
  4. 2

Which option accepts invalid documents but logs a warning?

  1. validationLevel: 'moderate'
  2. validationAction: 'warn'
  3. validationLevel: 'off'
  4. bypassDocumentValidation: false

A validator requires qty: { bsonType: 'int' }. Why is { qty: 2 } from mongosh rejected?

  1. 2 is too small
  2. mongosh stores 2 as a double
  3. Validators don't support numbers
  4. qty is a reserved name