Horje
Bypass Schema Validation in MongoDB

Schema Validation in MongoDB allows defining a structure for documents within a collection, ensuring data integrity and consistency. This validation ensures that documents adhere to specified rules upon insertion and updates.

In this article, We will learn about the Bypass Schema Validation in MongoDB in detail by understanding various things like their Supported Operations and what is Schema Validation.

Schema Validation in MongoDB

  • MongoDB documents are in BSON format and can be in any form. There are instances where a document should be in a specific structure.
  • Schema Validation in MongoDB enables to set the structure for the data in the document. Validation rules are defined for the schema when a collection is created.
  • This validation rule ensures that the data to be inserted follows the specified criteria.
  • If a document is updated with the new values, updated values must also follow the validation rule. The validation rule can contain required fields, BSON type and descriptions for fields in the collection.
  • The documents that satisfy Validation rules are called valid documents and those that don’t satisfy are invalid documents.

Bypass Schema Validation in MongoDB

  • Documents in the collection follow the validation rule if they are mentioned during the creation of the collection.
  • There are instances when a collection’s schema validation rules are bypassed. Validation rules are bypassed when restoring invalid data from the backup to a collection.
  • Old documents may not follow the new validation rules. Documents that bypass the validation rule during restoration or in another scenario must also bypass schema validation or become valid during future updates.

Supported Operations

  • Insert Commands: insertOne() and insertMany() commands insert one or multiple documents into a collection, bypassing schema validation if specified.
  • Update Commands: updateOne() and updateMany() commands update existing documents in a collection. They can bypass schema validation if required during updates.
  • Aggregation Operations: $out and $merge Stages stages in the aggregation pipeline allow outputting results into a new collection ($out) or merging results into an existing collection ($merge) bypassing schema validation.
  • Bulk Write Operations: bulkWrite() operation allows performing multiple write operations (inserts, updates, deletes) with optional bypass of schema validation.

Steps to Bypass Schema Validation in MongoDB

  • Step 1. Create a Collection with Validation Rules
  • Step 2. Bypass the Validation to Insert an Invalid Document
  • Step 3. Check Invalid Document Bypass Validation rule

Step 1. Create a Collection with Validation Rules

Let’s create an collection which is used in this article to perform operations and queries.

Query:

use database_name;
db.createCollection( ' Collection_name',
{ validator: { $jsonSchema : { details_about_collection} } });

We define with a particular name and create a Collection with validation rules using JSON schema.Through JSON schema we define the structure for the documents in the collection.

  • The createCollection() method is used to create a collection with a particular name.
  • validator is used to specify the validation rule which contains bsonType, required field, enum, minimum or maximum field.
  • $jsonSchema Used to define the JSON Schema, to specify validation rule and structure for a document in a collection.

Example: Create a Employee Collection with Validation Rules.

Query:

Let’s Create an collection called Employee in GeeksforGeeks database and applying structure and data integrity rules for employee documents

use GeeksforGeeks
db.createCollection("Employee", {
validator: {
$jsonSchema: {
bsonType: "object",
required: ["Name", "joining_year", "Address"],
properties: {
Name: {
bsonType: "string",
description: "Employee's name must be a string",
},
joining_year: {
bsonType: "int",
minimum: 2010,
maximum: 2024,
description:
"Employee's joining year must be an integer between 2010 and 2024",
},
Address: {
bsonType: "string",
description: "Employee's Address must be a string",
},
},
},
},
});

Output:

Create-collection-with-validation-rule

Create collection with validation rule

Explanation: Employee collection is created in GeeksforGeeks database. Collection is created using validation rule using JSON schema for the three fields. Fields in the document are [Name, joining_year,Address] .For each field bsontype and description is provided.

Step 2: Bypass the Validation to Insert an Invalid Document

In this step, as per requirements invalid document bypass the validation rule. insert command is used to bypass the validation rules of the collection. bypassDocumentValidation is set to true.

Example:

Following Document is invalid as it don’t satisfy the validation rule for the joining_year field.

Query:

{
Name:"Anil",
joining_year:2005,
Address:"Delhi"
}

Shema validation is bypassed using insert command ,bypassDocumentValidation option is set to true.

Query:

Let’s insert into the Employee Collection which violates the validation rules and requires a bypass to ensure successful insertion.

db.runCommand({
insert: "Employee",
documents: [
{
name: "Anil",
joining_year: 2005,
Address: "Delhi"
}
],
bypassDocumentValidation: true
})

Output:

Bypass-the-validation-to-insert-an-invalid-Document

Bypass the validation to insert an invalid Document

Explanation: In the above example, document don’t satisfy the validation rule of the collection. It don’t satisfy the condition of the joining_year field. Minimum of the field is set to 2010 but 2005 is used. Hence to bypass the schema validation insert command and bypassDocumentValidation are used.

Step 3: Check Invalid Document Bypass Validation Rule

In this step, check whether invalid document successfully bypass the validation rule. Run the find() method to check the document has been inserted into the collection or not.

Query:

db.Employee.find()

Output:

Check-invalid-document-bypass-validation-rule

Check invalid document bypass validation rule.

Explanation: In the above example, Invalid document successfully bypass the schema validation and the find() method is used to check the document which are present in the collection.

Conclusion

Schema validation in MongoDB is crucial for maintaining structured data integrity within collections. While it ensures consistency, bypassing validation should be carefully managed to prevent unintended data inconsistencies. We have learned about the what is Schema Validation and and what is Bypass Schema Validation in MongoDB also Steps to Bypass Schema Validation in MongoDB in detail.

Frequently Asked Questions (FAQs)

Why is schema validation important in MongoDB?

Schema validation ensures that documents meet specified criteria, preventing data inconsistency and maintaining application integrity.

When should schema validation rules be bypassed in MongoDB?

Schema validation rules may need to be bypassed during data restoration or migration scenarios to accommodate legacy data or schema changes.

What happens if a document bypasses schema validation in MongoDB?

Bypassing schema validation allows documents that do not meet defined rules to be inserted or updated, potentially leading to data integrity issues.

Which MongoDB operations support bypassing schema validation?

Operations like insertMany, insertOne, updateOne, updateMany, and aggregation stages like $out and $merge support bypassing schema validation when necessary




Reffered: https://www.geeksforgeeks.org


Databases

Related
MariaDB Function MariaDB Function
SQLite Dump Command SQLite Dump Command
SQLite Except Operator SQLite Except Operator
SQL Server Common Table Expressions SQL Server Common Table Expressions
SQLite Union Operator SQLite Union Operator

Type:
Geek
Category:
Coding
Sub Category:
Tutorial
Uploaded by:
Admin
Views:
14