Wednesday, 9 June 2021

MongoDB: validationLevel and validationAction

While setting the schema, you can additionally configure validationLevel and validationAction.

 

a.   validationLevel: Which type of validation you want to perform. It determines how strictly MongoDB applies validation rules to existing documents during an update, and

b.   validationAction: what action to be performed on validation failure. It determines whether MongoDB should error and reject documents that violate the validation rules or warn about the violations in the log but allow invalid documents.

 

Following table summarizes the possible values for validationLevel

Value

Description

strict

It is the default validation level. MongoDB applies validation rules to all inserts and updates.

moderate

MongoDB applies validation rules to inserts and to updates to existing documents that already fulfill the validation criteria. If any existing documents do not fulfill the validation criteria are not checked for validity while updating the content.

 

Following table summarizes possible values for validationAction

 

Value

Description

error

MongoDB rejects any insert or update that violates the validation criteria.

warn

MongoDB logs any violations but allows the insertion or update to proceed.

 

Let’s create an employee collection and specify the schema with validationLevel and validationAction.

 

Step 1: Create an employee collection.

> db.createCollection('employee')
{ "ok" : 1 }
> 
> show collections;
audit
countryCapitals
employee
project

 

Step 2: Add schema to the employee collection.

db.runCommand( {
   collMod: "employee",
   validator : {
      $jsonSchema : {
         bsonType: 'object',
         required: ['empId', 'firstName', 'lastName'],

         properties: {
            empId : {
               bsonType : 'int',
               description: 'empId must be an integer and mandatory property'
            },
            firstName : {
               bsonType: 'string',
               description: 'firstName must be a string and mandatory property'
            },
            lastName : {
               bsonType: 'string',
               description: 'lastName must be a string and mandatory property'
            },
            hobbies : {
               bsonType : 'array',
               description: 'Hobbies of user',
               items: {
                  bsonType: 'int'
               }
            },
            projects : {
               bsonType : 'array',
               description: 'Hobbies of user',
               required: ['pjtName', 'pjtId'],
               items: {
                  bsonType: 'object',
                  properties : {
                     pjtName : {
                        bsonType: 'string',
                        description: 'pjtName must be a string and mandatory property'
                     },
                     pjtId : {
                        bsonType: 'int',
                        description: 'pjtId must be a string and mandatory property'
                     }
                  }
               }
            }
         }

      }
   },
   validationLevel: "strict",
   validationAction: "error"
} )

 

Let’s try to insert some invalid information

Employee with only empId and firstName.

> db.employee.insert({"empId": 123, "firstName": "Sailu"})
WriteResult({
	"nInserted" : 0,
	"writeError" : {
		"code" : 121,
		"errmsg" : "Document failed validation"
	}
})
>
>
> db.employee.insert({"empId": NumberInt(123), "firstName": "Sailu"})
WriteResult({
	"nInserted" : 0,
	"writeError" : {
		"code" : 121,
		"errmsg" : "Document failed validation"
	}
})

 

Employee with empId, firstName and lastName properties

 

> db.employee.insert({"empId": NumberInt(123), "firstName": "Sailu", "lastName" : "PTR"})
WriteResult({ "nInserted" : 1 })

 

Let’s try to add project property and invalid information to project object

> db.employee.insert({"empId": NumberInt(234), "firstName": "Keerthi", "lastName" : "Shetty", "projects": [{"pjtName": "CPCS", "pjtId": 123}]})
WriteResult({
	"nInserted" : 0,
	"writeError" : {
		"code" : 121,
		"errmsg" : "Document failed validation"
	}
})

In the above example the property "pjtId" should be of type NumberInt. Let’s correct and insert the data.

 

> db.employee.insert({"empId": NumberInt(234), "firstName": "Keerthi", "lastName" : "Shetty", "projects": [{"pjtName": "CPCS", "pjtId": NumberInt(123)}]})
WriteResult({ "nInserted" : 1 })

Let’s print all the documents of employee collection.

> db.employee.find().pretty()
{
	"_id" : ObjectId("60c057188d62325981fe3cb4"),
	"empId" : 123,
	"firstName" : "Sailu",
	"lastName" : "PTR"
}
{
	"_id" : ObjectId("60c057488d62325981fe3cb6"),
	"empId" : 234,
	"firstName" : "Keerthi",
	"lastName" : "Shetty",
	"projects" : [
		{
			"pjtName" : "CPCS",
			"pjtId" : 123
		}
	]
}


Note

Schema validation will only apply to new write operations it will not run against existing documents in the collection.


 

Previous                                                    Next                                                    Home

No comments:

Post a Comment