MongoDB schema validation helps maintain data consistency while preserving MongoDB’s flexible document model. It allows you to define rules for document structure, required fields, data types, and permitted values using JSON Schema. It also demonstrates how MongoDB rejects documents that fail the defined rules, helping applications prevent unintended schema changes and invalid data.
Rexcily September 10, 2026
Relational databases, with their tables of rows and columns, stick to a fixed plan – a rigid schema with predefined data types for each field. On the flip side, document-oriented databases like MongoDB keep it simple and flexible. They let you tweak your document’s structure whenever you want.
However, even within the flexible landscape of MongoDB, there are scenarios where imposing certain structural guidelines on data becomes essential.
MongoDB addresses this need through a feature known as schema validation.
This functionality empowers users to enforce specific constraints on the structure of their documents, blending the freedom to adapt document structures with the necessity of maintaining a predefined framework.
At the core of MongoDB’s schema validation is the utilization of JSON Schema, an open standard designed for describing and validating the structure of JSON documents.
Introduced in 3.2, starting in version 3.6, MongoDB supports JSON Schema validation.
Creates a validation rule for the fields in the collection.
Once established an application schema, we can use schema validation to ensure there are no unintended schema changes or improper data types.
When we create a new collection with schema validation, MongoDB checks validation during updates and inserts in that collection.
If schema validation is added to an existing collection, newly inserted documents are checked.(Based on validation rules)
Schema validations can be categorized in two ways:
This is the default one and applies validation rules to all inserts and updates.
Applies validation rules to existing valid documents. Updates to invalid documents that exist prior to the validation being added are not checked for validity.
We can’t specify schema validation for:
Step 1: Assume a fixed plan and predefined data types for your collection.
Sample Data:
{ title: 'Love', price: 250, description: 'cute love story', authors: [ 'Jack', 'Rose' ], status: 'active', publisher: { name: 'Joan', address: 'Mafs' } }Step 2: Create a schema validation for your collection.
"testRepl" [direct: primary] Library> db.createCollection("books", { validator: { $jsonSchema: { bsonType: "object", required: ["title", "price", "description", "authors", "status", "publisher"], properties: { title: { bsonType: "string", description: "Title must be a string and is required" }, price: { bsonType: "number", description: "Price must be a number and is required" }, description: { bsonType: "string", description: "Description must be a string and is required" }, authors: { bsonType: "array", items: { bsonType: "string", description: "Authors must be a string" } }, status: { enum: ["active", "inactive"], description: "Can only be one of the enum values active or inactive" }, publisher: { bsonType: "object", required: ["name", "address"], properties: { name: { bsonType: "string", description: "Name must be a string and is required" }, address: { bsonType: "string", description: "Address must be a string and is required" } } } } } } })Step 3: Try to insert some data that does not match your validation rule.
"testRepl" [direct: primary] Library> db.books.insertOne({title: 'Horror',price:350,description:'Two Ghosts in a forest',authors:['John','Doe'],status:'Yes',publisher:{name:'Joan',address:'Cools'}})Uncaught:MongoServerError: Document failed validationAdditional information: { failingDocumentId: ObjectId("656993883e244ff468f287b2"), details: { operatorName: '$jsonSchema', schemaRulesNotSatisfied: [ { operatorName: 'properties', propertiesNotSatisfied: [ { propertyName: 'status', description: 'can only be one of the enum values active or inactive', details: [ { operatorName: 'enum', specifiedAs: { enum: [ 'active', 'inactive' ] }, reason: 'value was not found in enum', consideredValue: 'Yes' } ] } ] } ] }}Here we have inserted the “status:’Yes’ “ which does not match our validation rule, and thereby it throws an error.
Step 4: Try to insert some data which match our validation rule.
"testRepl" [direct: primary] Library> db.books.insertOne({title: 'Horror',price:350,description:'Two Ghosts in a forest',authors:['John','Doe'],status:'active',publisher:{name:'Joan',address:'Cools'}}){ acknowledged: true, insertedId: ObjectId("656993793e244ff468f287b1")}Here we go, data inserted successfully without any errors.
Schema validation is a nice feature to have if the business needs to have a fixed schema.
At Mafiree, we’ve got your back when it comes to tailoring your databases to suit your unique requirements.
We provide 24x7 support for MongoDB servers, which includes performance tuning of MongoDB servers, version upgrades, query optimization, including fine-tuning of aggregation queries, and configuration of full and incremental backups based on business needs.
If you’ve got any questions or need assistance, feel free to drop us a line at support@mafiree.com. We’re here to make your database journey smoother!
Miru IT Park, Vallankumaranvillai,
Nagercoil, Tamilnadu - 629 002.
Unit 303, Vanguard Rise,
5th Main, Konena Agrahara,
Old Airport Road, Bangalore - 560 017.
Call: +91 6383016411
Email: sales@mafiree.com