Schema Validation in MongoDB
Last Updated :
17 Oct, 2024
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 Schema Validation in MongoDB, When to use Schema Validation and When MongoDB Checks Validation in detail by understanding various aspects
Mongodb Schema Validation
- Schema validation in MongoDB is a feature that allows us to set the structure for the data in the document of a collection.
- We follow some set of rules and validation rules which ensure that the data we insert or update follows a specific predefined schema and ensures the data must have only specific datatypes, required fields and validation expressions mentioned in the predefined schema.
- When we create a collection for the first time and we want it to meet specific criteria then we can define the collection with the schema validation rules.
- These validation rules can include specifying the required fields we want and the datatype for those fields and also allow the users custom expressions. We use the command $jsonSchema for specifying the rules.
When to use Schema Validation
- Schema validation sets rules for how documents should look in our database. When developing a new application, we might not want to use schema validation since the incoming data could change and we're still figuring out the structure.
- However, once we have a clear understanding of our application and know the types of data each field should hold, we can use schema validation. For example, if we have a collection to store employee usernames then we can set validation rules to ensure that usernames are always stored as strings. This prevents users from accidentally entering other data types.
- For instance, we have a collection 'students' and you want to have fields like name, id, age and department for our collection to store in it.
Step 1: We create a collection named of 'students' using the createCollection() command.
Step 2: With the '$jsonShema' command inside the validator we specify the schema validation rules. Here with the required property we give a list of fields that every document must have when inserted into the collection.
Step 3: Give all the fields and their datatypes inside the properties.
// Example schema validation for a collection named 'Students'
db.createCollection("Students", {
validator: {
$jsonSchema: {
bsonType: "object",
required: ["name", "id", "age", "department"],
properties: {
name: {
bsonType: "string",
description: "Name must be a string."
},
id: {
bsonType: "int",
description: "id must be an integer."
},
age: {
bsonType: "int",
minimum: 10,
description: "Age must be an integer greater than or equal to 10."
},
dept: {
bsonType: "string",
description: "Department must be a string."
}
}
}
}
});
Step 4: Now try to insert the documents one by one into the collection with insertOne() command.
Query:
When we insert data according to validation rules it means Valid Document.
//inserting a record into Students
db.Students.insertOne({
name: "el",
id: 2001,
age: 11,
department: "IS",
});
Output:
Document Inserted Successfully.When we will try to add Invalid Documents to our collection.
Query:
//inserting a record into Students
db.Students.insertOne({
name: "will",
id: 2002,
age: 14,
});
Output:
Document failed to insert due to validation.Explanation: Here, you can see the first document consists of all the required fields in the collection so it is inserted successfully. Whereas, the second document is missing the department field, in this case it is considered an invalid document and throws an error as it doesn't meet the criteria specified in the schema validation. Hence MongoDB rejects the document to be inserted into the collection.
When MongoDB Checks Validation
We should know that whenever we create a new collection with schema validation, MongoDB checks for validations only during updates and inserts in that collection. When we specify validation rules for a pre-existing, non-empty collection only the documents that are inserted after are checked for validations.
The documents already present in the collection are not checked for validation until they are altered. When we want to update the already existing schema we use 'collMod' command.
db.runCommand({
collMod: "Students",
validator: {
$jsonSchema: {
bsonType: "object",
required: ["name", "id", "age", "department", "marks"],
properties: {
name: {
bsonType: "string",
description: "Name must be a string.",
},
id: {
bsonType: "int",
description: "ID must be an integer.",
},
age: {
bsonType: "int",
minimum: 10,
description: "Age must be an integers greater than or equal to 10.",
},
department: {
bsonType: "string",
description: "Department must be a string.",
},
marks: {
bsonType: "int",
minimum: 0
description: "Marks must be integer greater than or equal to 0.",
},
},
},
},
});
Explanation: Here we included the marks field in the required property. We used 'collMod' to modify the schema defined earlier.
Note: 'collMod' will fail if the collection has the already existing documents that don't follow the validation rules. So to modify the schema with 'collMod', ensure that the documents already present in the collection must be updated according to the schema or removed.
What Happens When a Document Fails Validation
When a document fails schema validation in MongoDB:
- MongoDB rejects the document insertion or update.
- It returns an error specifying which validation rules the document violated.
- No changes are applied to maintain data integrity.
- Developers handle validation errors in application code.
- Schema updates may require modifying existing documents to match new rules.
Conclusion
In conclusion, using MongoDB schema validation is important for keeping your data accurate. By applying MongoDB validation rules, you can avoid mistakes and make your database stronger. Good MongoDB data validation leads to better data quality and smoother application performance.
Similar Reads
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 Val
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 MongoD
5 min read
Specify JSON Schema Validation in MongoDB
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 specifyi
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
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
Transactions in MongoDB
MongoDB is a popular NoSQL database known for its scalability and flexibility, but handling multiple operations across multiple documents and collections has always been a challenge for developers. With the introduction of multi-document ACID transactions in MongoDB 4.0, developers can now ensure da
7 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
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
Transactions in Mongoose
In modern web applications, maintaining data integrity across multiple database operations is crucial. Transactions in Mongoose allow developers to execute multiple database operations within a single transaction, ensuring that all operations are successful, or none are executed. This guarantees con
6 min read
MongoDB $in Operator
MongoDB $in operator provides a powerful way to query documents based on multiple potential values for a specific field within a single query.In this article, We will learn about the MongoDB $in Operator by understanding various examples in detail.MongoDB $in OperatorThe MongoDB $in operator is used
4 min read