JSON Schema Validation Rules
Intermediate12 min
Enforce data integrity in MongoDB by defining JSON Schema validation rules that reject documents not matching your expected structure.
Prerequisites
- -MongoDB 6+ with mongosh
- -Understanding of JSON Schema basics
Steps
1
Create a collection with schema validation
Define a collection with JSON Schema rules that enforce required fields and types.
$ mongosh --eval 'db.createCollection("products", {validator: {$jsonSchema: {bsonType: "object", required: ["name", "price", "category"], properties: {name: {bsonType: "string", description: "must be a string"}, price: {bsonType: "number", minimum: 0, description: "must be a non-negative number"}, category: {enum: ["electronics", "clothing", "food", "books"], description: "must be a valid category"}, inStock: {bsonType: "bool"}}}}})' mydb
2
Test validation with a valid document
Insert a document that passes all validation rules.
$ mongosh --eval 'db.products.insertOne({name: "Laptop", price: 999.99, category: "electronics", inStock: true})' mydb
3
Test validation with an invalid document
Attempt to insert a document that violates the schema to verify enforcement.
$ mongosh --eval 'try { db.products.insertOne({name: "Bad Product", price: -10, category: "invalid"}); } catch(e) { print("Validation error: " + e.message); }' mydb
The insert will fail with a document validation error showing which rules were violated.
4
Add validation to an existing collection
Apply schema validation rules to a collection that already has data.
$ mongosh --eval 'db.runCommand({collMod: "orders", validator: {$jsonSchema: {bsonType: "object", required: ["customerId", "items", "total"], properties: {customerId: {bsonType: "string"}, items: {bsonType: "array", minItems: 1}, total: {bsonType: "number", minimum: 0}}}}, validationLevel: "moderate"})' mydb
validationLevel 'moderate' only validates inserts and updates to documents that already match the schema. Use 'strict' to validate all writes.
5
View current validation rules
Inspect the validation rules configured on a collection.
$ mongosh --eval 'db.getCollectionInfos({name: "products"})[0].options.validator' mydb
Full Script
FAQ
Discussion
Loading comments...