Specify Validation With Query Operators in MongoDB
Last Updated :
09 Jul, 2024
Validation rules in MongoDB define the structure and content requirements for collections by ensuring data integrity by allowing only valid documents to be inserted. By using query operators, MongoDB validators enforce rules such as field types, required fields and allowable values and thereby preventing invalid data from entering the database.
In this article, We will learn about the Specify Validation With Query Operators in MongoDB by understanding various things in detail.
Validation Rules in MongoDB
- Validation rules in MongoDB 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
- Create a Collection with a Validation.
- Confirm that the validation prevents invalid documents.
- 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 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. Confirm that the 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 DocumentExplanation: 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.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.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.
Similar Reads
MongoDB - Logical Query Operators
Logical query operators in MongoDB are fundamental tools used to combine or modify the results of queries using logical conditions. These operators empower developers to create complex queries by combining multiple conditions and enabling precise filtering of documents based on various criteria.In t
4 min read
MongoDB Query and Projection Operator
MongoDB query operators play a crucial role in interacting with data stored in MongoDB collections. Similar to SQL, these operators enable users to filter, compare, and manipulate data efficiently. Query operators allow for value-based comparisons, logical evaluations, and array operations, making d
11 min read
MongoDB - Comparison Query Operators
MongoDB provides powerful comparison query operators to filter and retrieve documents based on field values. These operators help developers perform precise queries, enabling efficient data retrieval and manipulation. MongoDB uses various comparison query operators to compare the values of the docum
4 min read
MongoDB - Field Update Operators
MongoDB offers a range of powerful field update operators that enable efficient modification of specific fields within documents. These operators allow developers to update specific fields in documents without rewriting the entire document, thus improving performance and operational efficiency.By gu
5 min read
MongoDB - $setOnInsert Operator
The $setOnInsert operator in MongoDB is a powerful tool used in updating operations with the upsert option. It allows us to specify values that should be set only when a new document is inserted. In this article, we will learn about the $setOnInsert Operator in MongoDB in detail and so on. MongoDB $
4 min read
MongoDB Update Operators
MongoDB update operators offer powerful tools for modifying documents within a collection which provides flexibility and efficiency in database operations. From setting and unsetting fields to manipulating arrays and applying bitwise operations. In this article, we will understand different Update O
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
MongoDB - Positional Operator ($)
MongoDB provides a variety of array update operators to modify the values within array fields in documents. One such operator is the positional operator $. This operator allows us to update an element in an array without explicitly specifying the position of that element. In this article, We will le
4 min read
MongoDB All Positional Operator ($[])
The MongoDB $[] positional operator is a powerful tool used to update all elements in an array that match a specified condition. When working with arrays in MongoDB, this operator helps identify and modify every element that meets the query criteria. In this article, We will learn about the MongoDB
4 min read
Python MongoDB - Update_many Query
MongoDB is  a NoSQL database management system. Unlike MySQL the data in MongoDB is not stored as relations or tables. Data in mongoDB is stored as documents. Documents are Javascript/JSON like objects. More formally documents in MongoDB use BSON. PyMongo is a MongoDB API for python. It allows to re
3 min read