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.

Syntax:-

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 tutorialtous.com domain
4 country string only of (UK,INDIA)
5 pincode String type min and max chars 5

Now validator is as follows

>db.createCollection("address",{
    validator:{
        firstname:{$type:"string"},
        lastname:{$type:"string"},
        emailid:{$type:"string",$regex:/@TutorialToUs\.com/},
        country:{$in:["UK","INDIA"]},
        pincode:{$type:"string",$regex:/...../}
    }
    })

Sample Valid Insertions:-

>db.address.insert({firstname:"Sachin",lastname:"Tendulkar"
,emailid:"Sachin@TutorialToUs.com",country:"INDIA",pincode:"400001"})

Sample Invalid Insertions:-

1. (invalid mail id)

>db.address.insert({firstname:"Dravid",lastname:"Rahul"
,emailid:"TutorialToUs.com",pincode:"400001",country:”INDIA”})

2. (invalid country)

>db.address.insert({firstname:"Dravid",lastname:"Rahul"
,emailid:"Rahul@TutorialToUs.com",pincode:"400001",country:”IN”})

3. (omition of mailid)

>db.address.insert({firstname:"Dravid",lastname:"Rahul"
,pincode:"400001",country:”INDIA”})

Copyright © 2018-2020 TutorialToUs. All rights reserved.