Modify Schema Validation in MongoDB
Last Updated :
31 Jul, 2024
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 Validation in MongoDB in detail.
Validation Rule in MongoDB
- Validation rules decide the structure of the collection.
- The documents that satisfy the Validation rule are called valid documents and those that don't satisfy are invalid documents.
- Validation rules can be changed at any time. Validation rules are modified using the collMod command in the validator object.
- Validation level, Validation rules and Validation action can be also modified.
When should we Modify Schema Validation in MongoDB?
As there are changes in data requirements or the business logic, schema validation rules are modified.
Points to remember:
- Initially, valid documents can change to invalid after modification in validation rules if they don't satisfy the new rule.
- Validation rules can be applied to a collection that was defined without validation rules.
Steps to Modify Schema Validation in MongoDB
- Create a collection with validation.
- Modify the validation schema.
Results After Modify the Schema:
Due to the changes in the validation rules following results occur
- Insert an Invalid Document.
- Insert a Valid Document.
- Handle a Previously Valid Document That Is No Longer Valid.
1. Create a collection with validation.
First define the database which is to be used.Collection is created with validation rules using JSON Schema. Structure for the documents in the collection is defined using validation rules.
Syntax:
use database_name;
db.createCollection( ' Collection_name',
{ validator: { $jsonSchema : { details_about_collection} } });
Explanation:
- The createCollection() method is used to prepare a collection with a particular name.
- validator is used to specify the validation rule which contains bsonType, required field, enum, minimum or maximum field.
- $jsonSchema Used to define the JSON Schema to specify validation rule and structure for a collection.
Example:
Create a collection with validation.Explanation: In the above example, voter collection is created using validation rules and two valid documents are inserted in it.
2. Modify the Validation Schema.
In this step, changes are made in the validation schema as per the new requirements.
Syntax:
db.runCommand( { collMod : "Collection_name ",
validator: { $jsonSchema : { details_about_collection_with_changes} } } ) ;
Explanation:
- runCommand() command is used to execute database commands. It is used for performing operations on the collection ,managing the user, and many more functions.
- collMod is used to modify the attributes of collections.
- $jsonSchema is used to set the structure of the document and is used during creation or updating the validation rules.
Modify the Validation Schema.Explanation:
- In the example mentioned ,validation rules are modified using runCommand method and collMod command. The minimum age in the validation rule is changed from 18 to 21.
- Validation level for the schema is strict hence the documents that do not satisfy the new validation rules changes to invalid document.
- There are 3 results that arises due to changes in the validation rule.
Results
1. Insert an Invalid Document
In this result, document is inserted according to the old validation rules. This document is now turned into invalid document as it don't satisfy new rules. The invalid document is prevented from insertion into the collection.
- insertOne() is use to insert the one document in the collection. The insertMany() is used to insert more than one document.
Insert an Invalid DocumentExplanation: In the above example,user attempts to insert a document according to old validation rule but fails as there are changes in the validation rules. This is one of the result due to changes in the validation rules.
2. Insert a Valid Document
In this result, a document is inserted according to the new validation rules and the document is successfully inserted into the collection.
Insert a Valid DocumentExplanation: In the above example, one document is successfully inserted in the collection which is according to new validation rules.
3. Handle a Previously Valid Document That Is No Longer Valid
- Database administrators need to handle the documents that are in a collection and have become invalid due to changes in the schema validation rules.
- These invalid documents are handled based on their validation level specified in the schema.
- If the validationLevel is strict then it must satisfy the new validation rules, if it is moderate then the document would not need to match.
- Users can check for the documents that don't satisfy using the following syntax.
Syntax:
db.runCommand( { validate:"Collection_name" , full :true });
Explanation:
- runCommand() command is used to execute database commands. It is used for performing operations on the collection ,managing the user, and many more functions.
- validate is used to check a correctness of the collection. It provide various details such as nInvalidDocument,nIndexes,records,errors ,warning,advice and many more.
Check for the invalid document.DBA can update or remove the invalid documents from the collection for the consistency of data.
For Update : db.collection_name.update( { match_condition } , { $set :{ value_to_update}} ,{multi: true} );
To delete: db.collection_name.deleteMany( { match_condition } );
- The update() function is used to modify documents based on specified conditions and update parameters.
- deleteMany() is use to remove more than one document from the collection based on the condition.
Handle a Previously Valid Document That Is No Longer ValidExplanation: In the above code invalid documents are removed. This helps to handle a previous valid document that is no longer valid.
Conclusion
Schema Validation decide the structure of the documents in MongoDB. Validation rules are modified using collMod command. Modified schema results in three outcomes ,which are handled and thus the process is completed. This helps to meet the current requirements, to ensure consistency and correctness to the documents.
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
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 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
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
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
Modify Valid or Invalid Documents in MongoDB
In MongoDB, maintaining data consistency and integrity is crucial especially when working with collections that have specific validation rules. A document is considered valid if it follows to the predefined schema or validation rules of a collection otherwise, it is invalid. In this article, we will
4 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