Specify JSON Schema Validation in MongoDB
Last Updated :
11 Feb, 2025
MongoDB is a flexible, scalable, and powerful NoSQL database, and one of its notable features is JSON Schema Validation. This feature allows developers to enforce data integrity within MongoDB collections, ensuring that documents inserted into a collection adhere to a specific structure. By specifying a set of validation rules, we can prevent erroneous data and maintain consistency across documents.
In this article, we will explain how to specify JSON Schema Validation in MongoDB and explore its practical implementation, ensuring that our MongoDB collections maintain the required structure and integrity.
What is JSON Schema Validation in MongoDB?
JSON Schema Validation in MongoDB allows us to enforce constraints on documents inserted into collections. These constraints ensure that documents conform to a defined structure, improving data consistency, and preventing invalid entries from being added to our database.
By using $jsonSchema in MongoDB, we can define validation rules for fields in a document. These rules can specify data types, required fields, patterns (like regex for emails), and other conditions that documents must meet.
Step 1: Creating a JSON Schema
In this step, We will Create a JSON object that will specify the validation rules that need to be set on the MongoDB collection. It will specify the validation rules on all the properties of the collection.
First, let's create a JSON schema that we will use as a validation while creating new entities inside the collection. Let's create a Schema that takes in first name, last name, and email, and the email should be valid, and all of them will be required.
The JSON that we will use for the Schema Validation:
{
$jsonSchema: {
bsonType: "object",
properties: {
first_name: {
bsonType: "string",
description: "must be a string",
},
last_name: {
bsonType: "string",
description: "must be a string",
},
age: {
bsonType: "int",
description: "must be an integer",
},
email: {
bsonType: "string",
pattern: "^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$",
description: "must be a valid email address",
},
},
}
}
Step 2: Adding the JSON Schema Validation to the Collection
In this Step, We will pass the above created JSON as an argument to the db.createCollection() command, so as to add the JSON Schema validation to the created collection.
Now, let's create a collection with the name, Users, and add the validation to the collection. The collection will contain first_name, last_name, age, and email as fields.

Explanation: In this step, the schema validation is applied to the users collection. The validator key ensures that any document inserted into this collection will be validated against the defined schema.
Step 3: Adding Documents to the Collection
Once the schema is in place, we can begin adding documents to the collection. Let’s explore how MongoDB handles documents that pass or fail schema validation.
Part A: Adding a Document with Invalid Data
In this step, we will try to add a document that does not create any cause against to the JSON validation rules.
Now, if we try to add a document that doesn't meet the validation criteria, then we will get a MongoDB validation error. In the image below, we try to add a user with an invalid email, and so we get a validation error.

Explanation: In the above image, we can see that the document does not get added to the collection. The document fails validation because the email format doesn’t match the specified pattern (it should be a valid email address). MongoDB prevents this invalid data from being inserted into the collection.
Part B: Adding a Document with Valid Data
In this step, we will try to add a document that does follows to the JSON validation rules.
If we try to add a document that follows the required validation criteria, then we are able to add the document successfully to the Collection. In this image below, we insert a new user with the correct email this time, and the user gets successfully added to the users collection.

Explanation: In the above image, we can see that the document gets added successfully to the collection. This document passes the validation rules, as the email is valid, and all required fields are provided.
Benefits of JSON Schema Validation in MongoDB
- Data Integrity: Schema validation helps ensure that only valid data is inserted into your collections. By defining clear rules for document structure, you can avoid issues with malformed data, reducing errors in your application.
- Consistency: By enforcing data types and validation rules, MongoDB helps maintain consistency across documents. This is especially important in applications that rely on specific data formats.
- Prevents Invalid Data: JSON Schema Validation prevents invalid or incomplete data from being inserted into the collection, which is critical for applications that require strict data accuracy.
Conclusion
In conclusion, we learned how to specify JSON schema validation in MongoDB, ensuring that documents inserted into our collections meet predefined structural rules. This feature is essential for maintaining data integrity, consistency, and preventing errors. By using $jsonSchema, MongoDB allows developers to set validation rules for fields, enforce correct data types, and validate formats like email addresses. By adopting JSON schema validation in our MongoDB collections, we ensure that our application maintains high-quality data and operates smoothly, even as the database grows.
Similar Reads
Schema Validation in MongoDB
MongoDB schema validation helps keep your data organized and correct. With MongoDB validation rules, we can set up guidelines for what data can be stored in our database. This makes it easier to ensure that all the information we save is reliable and useful. In this article, We will learn about the
6 min read
Modify Schema Validation in MongoDB
MongoDB Validation rules are essential for defining the structure and ensuring the integrity of documents within a collection. These rules determine what constitutes valid and invalid documents and can be modified as data requirements evolve. In this article, We will learn about the Modify Schema Va
6 min read
Bypass Schema Validation in MongoDB
Schema Validation in MongoDB allows defining a structure for documents within a collection, ensuring data integrity and consistency. This validation ensures that documents adhere to specified rules upon insertion and updates. In this article, We will learn about the Bypass Schema Validation in Mongo
5 min read
Specify Validation With Query Operators in MongoDB
Validation rules in MongoDB define the structure and content requirements for collections by ensuring data integrity by allowing only valid documents to be inserted. By using query operators, MongoDB validators enforce rules such as field types, required fields and allowable values and thereby preve
5 min read
How to Create and Validate JSON Schema in MongoDB?
JSON Schema validation in MongoDB allows you to enforce the structure of documents in a collection. This ensures data integrity by validating documents against defined schemas before they are inserted or updated. In this article, we will cover how to create and validate JSON Schema in MongoDB using
5 min read
View Existing Validation Rules in MongoDB
MongoDB is a NoSQL database. MongoDB database can handle large, complex, and unstructured data with easy scalability. It allows us to make changes to the Schema as and when required. The Schema validation rules are a set of rules that are applied to the document when it is added to the collection. I
3 min read
What is SchemaType in Mongoose ?
Mongoose is an Object Data Modeling (ODM) library for MongoDB and it provides a rich set of schema types to define the structure and data types of the documents stored in a MongoDB collection. A schemaType is used to define the data type and validation rules for a specific field in a schema. Syntax:
5 min read
How to Validate JSON Schema ?
Validating JSON schema ensures that the structure and data types within a JSON document adhere to a predefined schema. This process is crucial for ensuring data consistency and integrity in applications where JSON data is exchanged. ApproachImport the Ajv Library, a popular JSON Schema validator for
2 min read
How to Join two Schemas in Mongoose?
Mongoose is a popular MongoDB object modeling tool for Node.js that simplifies data manipulation. However, developers often face challenges when trying to join two schemas in Mongoose, as MongoDB, a NoSQL database, does not natively support join operations like SQL databases. In this article, We wil
5 min read
Mongoose Validation
Mongoose is an elegant solution for modeling and managing MongoDB data in a Node.js environment. One of its powerful features is data validation which ensures that data is correctly formatted and meets specific business rules before being saved to the database. This article explores Mongoose validat
6 min read