MongoDB provides document validation capabilities to enforce rules on the structure and content of documents stored in collections.
Document validation ensures that data inserted or updated in a collection adheres to predefined rules, such as field types, value ranges, presence of certain fields, and more.
This helps maintain data integrity and consistency within the database.
Document validation rules are specified using JSON Schema validation expressions.
MongoDB supports a subset of JSON Schema validation features for document validation.
{ $jsonSchema: { bsonType: "object", required: ["firstName", "lastName", "age", "profession"], properties: { firstName: { bsonType: "string", description: "must be a string and is required" }, lastName: { bsonType: "string", description: "must be a string and is required" }, age: { bsonType: "int", minimum: 0, maximum: 120, description: "must be an integer in the range [0, 120]" }, profession: { bsonType: "string", description: "must be a string and is required" }, } } }
bsonType: Specifies the type of the field.
required: Specifies the required fields.
properties: Defines the properties of the document and their validation criteria.
To enable document validation on a collection, we can specify validation rules when creating the collection or add validation rules to an existing collection using the "collMod" command.
Create Collection with Validation In MongoDB.
db.createCollection("your_collection_name", { validator: { { $jsonSchema: { bsonType: "object", required: ["firstName", "lastName", "age", "profession"], properties: { firstName: { bsonType: "string", description: "must be a string and is required" }, lastName: { bsonType: "string", description: "must be a string and is required" }, age: { bsonType: "int", minimum: 0, maximum: 120, description: "must be an integer in the range [0, 120]" }, profession: { bsonType: "string", description: "must be a string and is required" }, } } } } })
db.runCommand({ collMod: "your_collection_name", validator: { $jsonSchema: { bsonType: "object", required: ["firstName", "lastName", "age", "profession"], properties: { firstName: { bsonType: "string", description: "must be a string and is required" }, lastName: { bsonType: "string", description: "must be a string and is required" }, age: { bsonType: "int", minimum: 0, maximum: 120, description: "must be an integer in the range [0, 120]" }, profession: { bsonType: "string", description: "must be a string and is required" }, } }, validationLevel: "strict", validationAction: "error" })
Note: Adding Validation Rules to an Existing Collection:
MongoDB provides options to control the behavior of document validation:
validationLevel: Specifies the strictness of validation. It can be "off", "strict", or "moderate".
validationAction: Specifies the action to take when a validation rule is violated. It can be "error" or "warn".