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.
Data Consistency Requirements - When your application demands a consistent and well-defined structure.
Enforcing Business Rules - Rules related to data formats, ranges, or relationships between fields.
Healthcare Records - Ensures that critical information like patient demographics, medical history, and test results follows a predefined format.
Financial Transactions - Validating the format of transaction amounts, ensuring proper currency codes.
User Profiles in Social Networks - Ensuring that user profiles have required fields like username, profile picture and bio maintaining a standardized presentation.
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 inserting documents are checked.(Based on validation rules)
Schema validations can be categorized in two ways:
Strict:
This is a default one and applies validation rules to all inserts and updates.
Moderate:
Applies validation rules to existing valid documents. Updates to invalid documents which 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 which 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 therby 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 succesfully without any errors.
Schema validation is a nice feature to have if the business needs to have 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 upgrade, query optimization including fine tuning of aggregation queries, 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