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.T he 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.
Explanation: 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.
Explanation: 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.
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.
Explanation: In the above code invalid documents are removed. This helps to handle a previous valid document that is no longer valid.
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.