Mafiree logo
  • About
  • Services
  • Blogs
  • Careers
  • Products
    • orbit logo Orbit
    • streamer logo Xstreami
  • Contact
Schedule a Call
Menu
  • About
  • Services
  • Blogs
  • Careers
  • Products
    • orbit logo Orbit
    • streamer logo Xstreami
  • Contact
  • Schedule a Call
Database
Database Database Managed Services
MySQL MySQL
MySQL Consulting Services
MySQL Migration Services
MySQL Optimization & Query Tuning
MySQL Database Administration
MySQL Backup & Recovery
MySQL Security & Maintenance
MySQL Cloud Services (AWS RDS, Aurora, Google Cloud SQL, Azure)
MySQL for Ecommerce
MySQL High Availability & Replication
MongoDB MongoDB
MongoDB Consulting Services
MongoDB Migration Services
MongoDB Optimization & Query Tuning
MongoDB Database Administration
MongoDB Backup & Recovery
MongoDB Security & Maintenance
MongoDB Cloud (Atlas)
MongoDB Solutions by Industry
MongoDB High Availability & Replication
PostgreSQL PostgreSQL
PostgreSQL Consulting
PostgreSQL Migration & Upgrades
Performance Tuning & Query Optimization
PostgreSQL Administration & Managed Services
High Availability, Clustering & Replication
PostgreSQL Backup, Recovery & Disaster Planning
PostgreSQL Security, Compliance & Auditing
PostgreSQL for Analytics & Data Warehousing
PostgreSQL on Cloud & Containers
PostgreSQL Extensions & Open-Source Integrations
PostgreSQL for Every Industry
SQL Server MSSQL
MSSQL Consulting Services
MSSQL Migration Services
MSSQL Optimization & Query Tuning Services
MSSQL Database Administration Services
MSSQL Backup & Recovery Services
MSSQL High Availability & Replication Services
MSSQL Security & Compliance Services
MSSQL Performance Monitoring & Health Checks
MSSQL Solutions by Industry
Aerospike Aerospike
Aerospike Consulting Services
Aerospike Migration Services
Aerospike Performance Optimization & Tuning
Aerospike Database Administration
Aerospike Backup & Recovery
Aerospike High Availability
Aerospike Cloud & Hybrid Deployments
Aerospike for Real-Time Applications (AdTech, FinTech, Retail, IoT)
Analytics DB
Analytics DB Analytics DB Services
Clickhouse Clickhouse
ClickHouse Consulting Services
ClickHouse Migration Services
ClickHouse Optimization & Query Tuning
ClickHouse Database Administration
ClickHouse Backup & Recovery
ClickHouse Security & Maintenance
ClickHouse Cloud Services (ClickHouse Cloud, AWS, GCP, Azure)
ClickHouse Solutions by Industry
ClickHouse High Availability & Replication
TiDB TiDB
TiDB Consulting & Architecture Planning
TiDB Administration & Maintenance
TiDB Security and Privacy Maintenance
TiDB Performance & Query Optimization
TiDB Migration Services
TiDB Backup & Disaster Recovery
TiDB High Availability Solutions
TiDB Solutions by Industry
TiDB Cloud Services
ScyllaDB ScyllaDB
ScyllaDB Consulting & Architecture Planning
ScyllaDB Administration & Maintenance
ScyllaDB Security and Privacy Maintenance
ScyllaDB Performance & Query Optimization
ScyllaDB Migration Services
ScyllaDB Backup & Disaster Recovery
ScyllaDB High Availability Solutions
ScyllaDB Solutions by Industry
ScyllaDB Cloud Services
DevOps
DevOps DevOps Services
Version Control Version Control
Kubernetes Kubernetes
Infrastructure Infrastructure Management
Web Servers Web Servers
Networking
Networking Networking Services
Basic Basic
Advanced Advanced
MySQL MySQL
MongoDB MongoDB
PostgreSQL PostgreSQL
MSSQL MSSQL
Aerospike Aerospike
Clickhouse Clickhouse
TiDB TiDB
ScyllaDB ScyllaDB
Version Control Version Control
Kubernetes Kubernetes
Infrastructure Infrastructure Management
Web Servers Web Servers
Basic Basic
Advanced Advanced
MySQL Consulting Services
MySQL Migration Services
MySQL Optimization & Query Tuning
MySQL Database Administration
MySQL Backup & Recovery
MySQL Security & Maintenance
MySQL Cloud Services (AWS RDS, Aurora, Google Cloud SQL, Azure)
MySQL for Ecommerce
MySQL High Availability & Replication
MongoDB Consulting Services
MongoDB Migration Services
MongoDB Optimization & Query Tuning
MongoDB Database Administration
MongoDB Backup & Recovery
MongoDB Security & Maintenance
MongoDB Cloud (Atlas)
MongoDB Solutions by Industry
MongoDB High Availability & Replication
PostgreSQL Consulting
PostgreSQL Migration & Upgrades
Performance Tuning & Query Optimization
PostgreSQL Administration & Managed Services
High Availability, Clustering & Replication
PostgreSQL Backup, Recovery & Disaster Planning
PostgreSQL Security, Compliance & Auditing
PostgreSQL for Analytics & Data Warehousing
PostgreSQL on Cloud & Containers
PostgreSQL Extensions & Open-Source Integrations
PostgreSQL for Every Industry
MSSQL Consulting Services
MSSQL Migration Services
MSSQL Optimization & Query Tuning Services
MSSQL Database Administration Services
MSSQL Backup & Recovery Services
MSSQL High Availability & Replication Services
MSSQL Security & Compliance Services
MSSQL Performance Monitoring & Health Checks
MSSQL Solutions by Industry
Aerospike Consulting Services
Aerospike Migration Services
Aerospike Performance Optimization & Tuning
Aerospike Database Administration
Aerospike Backup & Recovery
Aerospike High Availability
Aerospike Cloud & Hybrid Deployments
Aerospike for Real-Time Applications (AdTech, FinTech, Retail, IoT)
ClickHouse Consulting Services
ClickHouse Migration Services
ClickHouse Optimization & Query Tuning
ClickHouse Database Administration
ClickHouse Backup & Recovery
ClickHouse Security & Maintenance
ClickHouse Cloud Services (ClickHouse Cloud, AWS, GCP, Azure)
ClickHouse Solutions by Industry
ClickHouse High Availability & Replication
TiDB Consulting & Architecture Planning
TiDB Administration & Maintenance
TiDB Security and Privacy Maintenance
TiDB Performance & Query Optimization
TiDB Migration Services
TiDB Backup & Disaster Recovery
TiDB High Availability Solutions
TiDB Solutions by Industry
TiDB Cloud Services
ScyllaDB Consulting & Architecture Planning
ScyllaDB Administration & Maintenance
ScyllaDB Security and Privacy Maintenance
ScyllaDB Performance & Query Optimization
ScyllaDB Migration Services
ScyllaDB Backup & Disaster Recovery
ScyllaDB High Availability Solutions
ScyllaDB Solutions by Industry
ScyllaDB Cloud Services
  1. Home
  2. > Blogs
  3. > MongoDB
  4. > Schema Validation In MongoDB

Schema Validation In MongoDB

Discover MongoDB's Schema Validation and JSON Schema

Rexcily December 05, 2023

Subscribe for email updates

Introduction:

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.

Schema Validation

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.

Where To Use Schema Validation

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 MongoDB Checks Validation

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 validation Rules

Schema validations can be categorized in two ways:

  1. Strict
  2. Moderate

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.

Restrictions

We can’t specify schema validation for:

  1. Collections in the admin, local and config databases.
  2. System collections.

Applying Schema Validation

Step 1: Assume a fixed plan and predefined data types for your collection.

Sample Data:

 

 

  1. {
  2.         title: 'Love',
  3.         price: 250,
  4.         description: 'cute love story',
  5.         authors: [ 'Jack', 'Rose' ],
  6.         status: 'active',
  7.         publisher: { name: 'Joan', address: 'Mafs' }
  8.       }

Step 2: Create a schema validation for your collection.

  1. "testRepl" [direct: primary] Library> db.createCollection("books", {
  2.        validator: {
  3.          $jsonSchema: {
  4.            bsonType: "object",
  5.            required: ["title", "price", "description", "authors", "status", "publisher"],
  6.            properties: {
  7.              title: {
  8.                bsonType: "string",
  9.                description: "Title must be a string and is required"
  10.              },
  11.              price: {
  12.                bsonType: "number",
  13.                description: "Price must be a number and is required"
  14.              },
  15.              description: {
  16.                bsonType: "string",
  17.                description: "Description must be a string and is required"
  18.              },
  19.              authors: {
  20.                bsonType: "array",
  21.                items: {
  22.                  bsonType: "string",
  23.                  description: "Authors must be a string"
  24.                }
  25.              },
  26.              status: {
  27.                enum: ["active", "inactive"],
  28.                description: "Can only be one of the enum values active or inactive"
  29.              },
  30.              publisher: {
  31.                bsonType: "object",
  32.                required: ["name", "address"],
  33.                properties: {
  34.                  name: {
  35.                    bsonType: "string",
  36.                    description: "Name must be a string and is required"
  37.                  },
  38.                  address: {
  39.                    bsonType: "string",
  40.                    description: "Address must be a string and is required"
  41.                  }
  42.                }
  43.              }
  44.            }
  45.          }
  46.        }
  47.      })

Step 3: Try to Insert some data which does not match your validation rule.

  1. "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'}})
  2.  
  3. Uncaught:
  4. MongoServerError: Document failed validation
  5. Additional information: {
  6.   failingDocumentId: ObjectId("656993883e244ff468f287b2"),
  7.   details: {
  8.     operatorName: '$jsonSchema',
  9.     schemaRulesNotSatisfied: [
  10.       {
  11.         operatorName: 'properties',
  12.         propertiesNotSatisfied: [
  13.           {
  14.             propertyName: 'status',
  15.             description: 'can only be one of the enum values active or inactive',
  16.             details: [
  17.               {
  18.                 operatorName: 'enum',
  19.                 specifiedAs: { enum: [ 'active', 'inactive' ] },
  20.                 reason: 'value was not found in enum',
  21.                 consideredValue: 'Yes'
  22.               }
  23.             ]
  24.           }
  25.         ]
  26.       }
  27.     ]
  28.   }
  29. }

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.

  1. "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'}})
  2. {
  3.   acknowledged: true,
  4.   insertedId: ObjectId("656993793e244ff468f287b1")
  5. }

Here we go, data inserted succesfully without any errors.

Summary

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!

Author Bio

Rexcily

Rexcily Rijo is a MongoDB Certified DBA at Mafiree, with deep expertise in MongoDB database administration, performance optimization, and scalable data solutions. He writes practical, hands-on technical content focused on MongoDB internals, best practices for database operations, TTL and index strategies, and real-world techniques that help engineers and DBAs manage and optimize modern document databases.

Leave a Comment

Related Blogs

MongoDB Transactions: A Comprehensive Guide to ACID Compliance

MongoDB ensures data consistency with single-document atomic operations and multi-document transactions. This guide explains how to implement transactions, their limitations, performance impacts, and best practices for production environments. It also highlights when to use distributed transactions and how expert consulting can help optimize performance.

  881 views
Let MongoDB Clean Up After Itself: A Complete Guide to TTL Indexes

Tired of bloated log collections and messy data? TTL indexes in MongoDB automate your cleanup no cron jobs, no scripts. Learn how to set up, monitor, and optimize TTL for cleaner, faster, and self-maintaining databases.

  5214 views
Top 10 MongoDB Operators Every Developer Should Know (With Examples)

Unlock MongoDB’s full potential! Discover the most powerful MongoDB query operators to supercharge your queries with practical examples every developer can use. #MongoDB #DeveloperTips

  2849 views
Reclaiming MongoDB Storage Space: A Journey to 50% Space Reduction

Efficiently Reclaim Disk Space in MongoDB: Strategies and Solutions for Optimal Performance.

  2071 views
Don't Let Hackers In: How to Secure and Harden Your MongoDB Database

Learn how to protect your MongoDB database with robust security practices, including user authentication, encryption, IP whitelisting, and input validation. Ensure your data remains safe and accessible in today's evolving threat landscape.

  3717 views

Subscribe for email updates

Get in touch with us

Highlights

More than 6000 Servers Monitored

Happy Clients

Certified DBAs

24 x 7 x 365 Support

PCI

Database Services

MySQL MongoDB PostgreSQL SQL Server Aerospike Clickhouse TiDB MariaDB Columnstore

Quick Links

Careers Blog Contact Privacy Policy Disclaimer Policy

Contacts

Linkedin Mafiree Facebook Mafiree Twitter Mafiree

Nagercoil Office

Miru IT Park, Vallankumaranvillai,

Nagercoil, Tamilnadu - 629 002.

Bangalore Office

Unit 303, Vanguard Rise,

5th Main, Konena Agrahara,

Old Airport Road, Bangalore - 560 017.

Call: +91 6383016411

Email: sales@mafiree.com


Copyright © - All Rights Reserved - Mafiree