Document Validation In MongoDB

Document Validation

Most of the readers came from SQL think that MongoDB collections are not useful for practical work scenarios until they know this document validation concept.

To Create a document for the practical life we need to apply the document validators for the collection, means if we want to create the table with some rules and regulations like this field is accept only this data type, this field values must met some requirements like this then document validators are very essential.

MongoDB provides the capability to validate documents during updates and insertions. Validation rules are specified on a per-collection basis using the validator option, which takes a document that specifies the validation rules or expressions. Specify the expressions using any query operators, with the exception of $near, $nearSphere, $text, and $where.


db.createCollection(<name>,{validator:{some rules}})

Example:- Create a collection name 'address' with the following rules
sno field Details
1 firstname string type
2 lastname string type
3 emailId string type must be of domain
4 country string only of (UK,INDIA)
5 pincode String type min and max chars 5

Now validator is as follows


Sample Valid Insertions:-


Sample Invalid Insertions:-

1. (invalid mail id)


2. (invalid country)


3. (omition of mailid)


Copyright © 2018-2020 TutorialToUs. All rights reserved.