Configuring JSON Schema Validation in MongoDB (original) (raw)

Last Updated : 5 May, 2026

MongoDB’s JSON Schema Validation enforces structured rules on documents at the collection level, ensuring only valid and consistent data is stored while keeping NoSQL flexibility.

validation

Implementation Steps for JSON Schema Validation

A step-by-step process to define, apply, and test schema rules for ensuring valid data in MongoDB collections.

Step 1: Creating a JSON Schema

Create a $jsonSchema object to define validation rules for the collection. The schema enforces required fields (first_name, last_name, email) and validates data types, with a regex constraint to ensure email follows a valid format.

**The JSON that we will use for the Schema Validation:

{
$jsonSchema: {
bsonType: "object",
required: ["first_name", "last_name", "age", "email"],
properties: {
first_name: {
bsonType: "string",
description: "must be a string"
},
last_name: {
bsonType: "string",
description: "must be a string"
},
age: {
bsonType: "int",
description: "must be an integer"
},
email: {
bsonType: "string",
pattern: "^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$",
description: "must be a valid email address"
}
}
}
}

Step 2: Adding the JSON Schema Validation to the Collection

Pass the $jsonSchema validator to db.createCollection() to create the Users collection with enforced validation rules for first_name, last_name, age, and email.

Screenshot-2026-02-21-112743

Step 3: Adding Documents to the Collection

After defining the validator, insert operations are checked against the schema, documents that match the rules are accepted, while invalid documents are rejected with a validation error.

**Part A: Adding a Document with Invalid Data

Insert operations are validated against the schema: documents that satisfy all $jsonSchema constraints are accepted, while documents violating rules (e.g., invalid email format) are rejected with a MongoDB validation error.

Screenshot-2026-02-21-113046

**Part B: Adding a Document with Valid Data

Insert operations that satisfy all $jsonSchema constraints are accepted, documents meeting required fields and pattern validations (e.g., valid email format) are successfully written to the users collection.

Screenshot-2026-02-21-113210

Benefits of JSON Schema Validation

Here are the benefits of JSON Schema Validation: