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:
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.
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.
Modify Schema Validation in MongoDB
MongoDB was released in February 2009. It is an open-source document-oriented database. It is classified as a NoSQL database. The structure of the data in the collection is dynamic. It follows the CAP theorem (Consistency Availability and Partition tolerance). It is an unstructured language and provides horizontal scalability and high-performance, data persistence. It solved the problem of scalability and agility.