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
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
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
4 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 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 - 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 g
5 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
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 rea
3 min read
How to Use $set and $unset Operators in MongoDB
MongoDB is a NoSQL database that stores data in documents instead of traditional rows and columns found in relational databases. These documents, grouped into collections, allow for flexible data storage and retrieval. One of MongoDBâs key advantages is its ability to dynamically update documents us
7 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
MongoDB CRUD Operations by Modifying Query Results
MongoDB a NoSQL database is widely used for handling large amounts of unstructured or semi-structured data. It operates on a flexible document-based model, where data is stored in BSON (Binary JSON) format. One of the core functionalities of MongoDB is its CRUD (Create, Read, Update, Delete) operati
7 min read