Schema Validation with JSON Schema
Enforce data shape at the database boundary
Application validation is essential, but multiple services, scripts, migrations, or administrative tools may write to the same collection. MongoDB collection validation can reject documents that do not satisfy defined rules.
MongoDB supports JSON Schema validation with BSON-aware types. Use it to require fields, restrict types, enumerate allowed values, and define nested object shapes.
Example validator
db.createCollection("products", {
validator: {
$jsonSchema: {
bsonType: "object",
required: ["sku", "name", "price", "active"],
properties: {
sku: {
bsonType: "string",
description: "Stable stock keeping unit"
},
name: {
bsonType: "string",
minLength: 1
},
price: {
bsonType: ["int", "long", "double", "decimal"],
minimum: 0
},
active: {
bsonType: "bool"
},
tags: {
bsonType: "array",
items: { bsonType: "string" }
}
}
}
},
validationLevel: "strict",
validationAction: "error"
});
For money, consider storing values as Decimal128 or integer minor units rather than binary floating-point values, depending on the application's currency and arithmetic rules. Choose one representation consistently and validate it.
Validation levels and actions
validationLevel: "strict"applies validation to inserts and updates of documents.validationLevel: "moderate"applies validation to inserts and updates of documents that already satisfy validation, while allowing existing invalid documents to be updated without necessarily satisfying the new rule.validationAction: "error"rejects writes that fail validation.validationAction: "warn"permits the write but logs a warning.
Exact behavior and available validator features can vary with server version, so verify against the MongoDB version in use before deploying a validator.
Add validation to an existing collection
db.runCommand({
collMod: "products",
validator: {
$jsonSchema: {
bsonType: "object",
required: ["sku", "name"],
properties: {
sku: { bsonType: "string" },
name: { bsonType: "string", minLength: 1 }
}
}
},
validationLevel: "strict",
validationAction: "error"
});
Before switching to strict error behavior, inspect existing data and test the validator against representative documents. Validation does not automatically repair historical documents. It also does not replace authorization, business logic, uniqueness constraints, or careful transaction design.
- $jsonSchema:
A validator format for requiring fields and constraining BSON types and values. - validationAction: error:
Reject writes that fail validation. - validationAction: warn:
Allow writes while recording validation warnings.
Roll out strict validation only after auditing existing documents and testing all writers. A validator protects future writes; it does not clean up old data.
// With the validator above, this should be rejected because price is a string.
db.products.insertOne({
sku: "KB-900",
name: "Compact Keyboard",
price: "4999",
active: true
});
// Valid shape; use Decimal128 for exact decimal monetary representation.
db.products.insertOne({
sku: "KB-901",
name: "Wired Keyboard",
price: NumberDecimal("1999.00"),
active: true,
tags: ["keyboard", "wired"]
});- Use database validation as a shared safety boundary.
- Choose BSON types deliberately, especially for dates, identifiers, and monetary values.
- Audit legacy documents before enabling strict validation.
What does a collection validator primarily provide?