Open In App

Specify Validation With Query Operators in MongoDB

Last Updated : 03 Jan, 2024
Improve
Improve
Like Article
Like
Save
Share
Report

MongoDB was released in February 2009. It is an open-source document-oriented database. It is classified as a NoSQL database. Its schema is dynamic and is unstructured language. It follows the CAP theorem (Consistency Availability and Partition tolerance). It provides horizontal scalability and high-performance data persistence. It solved the problem of scalability and agility.

Validation Rules in MongoDB

Validation rules specify the required structure for the collection which can contain required fields, bsonType, and description for fields in the collection. These validation rules can also be applied using the query operators. Query operators can be logical, comparison, element, evaluation, or others. The documents that satisfy the validation rules are known as valid documents, while those that do not satisfy as invalid documents. Invalid documents are prevented from insertion into the collection.

Restrictions

We can’t specify the following query operators in a validator object:

  • $expr with $function expressions
  • $near
  • $nearSphere
  • $text
  • $where

Steps for Specifying Validation are

  1. Create a Collection with a Validation Rule.
  2. Validation Prevents Invalid Documents.
  3. Insertion of Valid Document.

1. Create a Collection with Validation Rule.

In this step collection is created with validation rule. Query operators are used in the validation rules.

Syntax:

use  database_name;
db.createCollection ( 'collection_name',  { validator : query_operator });

Explanation:

  • use database_name‘ is used to specify the name of the database which is to be used.
  • createCollection( )‘ method is used to prepare a collection with particular name. Validation rules can also be specified inside it.
  • The ‘validator‘ is used to specify the structure of the document, validation rule can contain bsonType, required field, enum , description, minimum or maximum .
  • query_operator can be logical, comparison, element, evaluation, geospatial operators, or various others.

    Create-a-collection-with-validation

    Create a collection with validation rule.

Explanation: In the above example, database used is ‘GFG‘ and collection name is ‘students‘. Fields in the collection are name, address, age. $and and $or are the logical query operators used in validation rule. $and is used explicitly to specify that all the fields specified in it must be present in the document. $or is used to specify the allowed values for the address field. $gte is a comparison operator. It is used for the age field to compare the age in the document. $type is used to specify the datatype of the fields.

2. Validation Prevents Invalid Documents

In this step, attempt is made to insert a document into the collection. If the document fails the validation rule it is prevented through the validation rules.

Syntax:

db.collection_name.insertOne(   {  documents_as_per _validation_rule}  );

Valid Document

Valid document follows the structure specified in the validation rule and gets successfully inserted into the collection.

  • insertOne() method is used to insert a document in the collection.
Valid-Document

Valid Document

Explanation: In the above example document is inserted according to validation rules.The document contains the value for the age field greater than 8, address from the allowed values and name as string type.

Invalid Document

Invalid document do not follow the structure specified in the validation rules and hence it is prevented from being inserted into the collection.

Validation prevents invalid documents.

Validation prevents invalid documents.

Explanation: Above example don’t satisfy the validation rule. It fails the condition of the age field. Hence the document is prevented from insertion in the collection. Error contains various details such as Id, clausesNotSatisfied, reason and many more details.

3. Insertion of Valid Document

To successfully add a document to the collection, validation rules should be followed. In earlier step invalid document is prevent from insertion. System provides the details about the error in the document. These error are to be resolve and valid document is then inserted.

db.collection_name.insertOne( {  documents_as_per _validation_rule} );

Example:

Insertion of Valid Document.

Insertion of Valid Document.

Explanation: In this example document is inserted according to validation rules. The document is same as the one that is used in step2 only the value of age has been changed. The new value of the age satisfy the validation rule. Hence the steps are completed.

Conclusion

Specifying the validation with query operator allows to enforce the specific criteria on the document. It is a simple process which contain creation of collection with validation rule and insertion of the document into the collection. It allows to ensure the data integrity and consistency of the document within the collection.


Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads