MongoDB is a NoSQL database that offers flexibility in how you structure your data. However, there comes a time when you need to enforce some level of validation for data integrity. MongoDB provides this via schema validation levels and actions. In this article, we’ll dive into which documents get validated, what happens if validation fails, and the difference between strict and moderate validation levels.
Schema Validation Basics
Before diving into the depths, let’s quickly look at how to define a schema validation rule. Assume you have a collection named students
and you want to ensure that every document has a name
field of type string
:
db.createCollection("students", {
validator: {
$jsonSchema: {
bsonType: "object",
required: ["name"],
properties: {
name: {
bsonType: "string",
description: "Name must be a string"
}
}
}
}
});
Which Documents Get Validated?
Strict Validation
In strict validation, all incoming writes (insert
, update
, replace
) must pass the schema validation.
Moderate Validation
Moderate validation only applies to documents that already meet the validation rules. New or updated documents that don’t meet the criteria will still be rejected.
What Happens If Validation Fails?
If validation fails, MongoDB will reject the operation and return an error. The database won’t update or insert the document until it passes the validation rules.
Strict vs. Moderate Validation
The main difference between strict and moderate validation lies in how they deal with existing documents that don’t meet the validation rules.
Strict Validation
- Applies to all inserts and updates.
- Existing documents that don’t meet the criteria can’t be updated unless they are fixed first.
Moderate Validation
- Applies only to documents that already meet the validation criteria.
- Existing documents that don’t meet the criteria can still be updated as long as the update doesn’t violate the schema.
To set or modify the validation level and action, you can use the collMod
command:
db.runCommand({
collMod: "students",
validator: { /* new validator */ },
validationLevel: "moderate"
});
Summary
MongoDB schema validation is a powerful feature that helps maintain data integrity. The two main validation levels, strict
and moderate
, offer different levels of rigidity to suit your application’s needs. Always remember to consider your application’s specific requirements when choosing a validation level.
,