Nearby lessons

6 of 22

🧾 MongoDB: JSON Schema Validation

📌 What is JSON Schema Validation?

MongoDB allows you to enforce a schema using $jsonSchema to ensure data consistency.

It validates documents before insertion or update, helping maintain clean and reliable data.

1️⃣ Creating a Collection with Name Validation

MongoDB Shell
NoSQL
Database
1db.createCollection("students", {
2 validator: {
3 $jsonSchema: {
4 required: ["name", "age"],
5 title: "Student Object Validation",
6 properties: {
7 name: {
8 bsonType: "string",
9 description: "Name must be a string and is required"
10 }
11 }
12 }
13 }
14});
Query Result
JSON Output
✅ A new collection "students" is created with validation enforcing that name must be a string.

2️⃣ Creating a Collection with Age Validation

MongoDB Shell
NoSQL
Database
1db.createCollection("students", {
2 validator: {
3 $jsonSchema: {
4 required: ["name", "age"],
5 title: "Student Object Validation",
6 properties: {
7 age: {
8 bsonType: "int",
9 minimum: 5,
10 maximum: 20,
11 description: "Age must be an integer between 5 and 20"
12 }
13 }
14 }
15 }
16});
Query Result
JSON Output
✅ "students" collection validates that 'age' must be an integer between 5 and 20.

3️⃣ Creating a Collection with Course Validation

MongoDB Shell
NoSQL
Database
1db.createCollection("students", {
2 validator: {
3 $jsonSchema: {
4 required: ["name", "age"],
5 title: "Student Object Validation",
6 properties: {
7 course: {
8 bsonType: "string",
9 enum: ["BCA", "BTECH", "BSC", "MCA", "MTECH"],
10 description: "Course must be one of: BCA, BTECH, BSC, MCA, MTECH"
11 }
12 }
13 }
14 }
15});
Query Result
JSON Output
✅ Enforces that 'course' field must match one of the predefined options.

4️⃣ Object Validation (Nested Objects)

MongoDB Shell
NoSQL
Database
1address: {
2 bsonType: "object",
3 required: ["street", "city", "zipCode"],
4 properties: {
5 street: {
6 bsonType: "string",
7 description: "Street must be a string and is required."
8 },
9 city: {
10 bsonType: "string",
11 description: "City must be a string and is required."
12 },
13 zipCode: {
14 bsonType: "int",
15 description: "Zip code must be an integer and is required."
16 }
17 }
18}
Query Result
JSON Output
✅ Validates nested 'address' object fields with types and required constraints.

5️⃣ Full Validation Example – Students Collection

MongoDB Shell
NoSQL
Database
1db.createCollection("students", {
2 validator: {
3 $jsonSchema: {
4 required: ["name", "age", "course"],
5 title: "Student Object Validation",
6 properties: {
7 name: {
8 bsonType: "string",
9 description: "Name must be a string and is required"
10 },
11 age: {
12 bsonType: "int",
13 minimum: 5,
14 maximum: 20,
15 description: "Age must be an integer between 5 and 20"
16 },
17 course: {
18 bsonType: "string",
19 enum: ["BCA", "BTECH", "BSC", "MCA", "MTECH"],
20 description: "Course must be one of the following: BCA, BTECH, BSC, MCA, MTECH"
21 }
22 }
23 }
24 }
25});
Query Result
JSON Output
✅ Creates a collection with full schema validation for 'name', 'age', and 'course' fields.

6️⃣ Valid Insert Example

MongoDB Shell
NoSQL
Database
1db.students.insertOne({
2 name: "Rajesh Rathwa",
3 age: 20,
4 course: "BCA"
5});
Query Result
JSON Output
{
acknowledged: true,
insertedId: ObjectId('67c07db7dd5d0f9807cb0ce3')
}

7️⃣ Invalid Insert – Age Exceeds Limit

MongoDB Shell
NoSQL
Database
1db.students.insertOne({
2 name: "Rajesh Rathwa",
3 age: 25,
4 course: "BCA"
5});
Query Result
JSON Output
❌ Error: Document failed validation – Age must be between 5 and 20.

8️⃣ Invalid Insert – Name Not a String

MongoDB Shell
NoSQL
Database
1db.students.insertOne({
2 name: 50,
3 age: 20,
4 course: "BCA"
5});
Query Result
JSON Output
❌ Error: Document failed validation – Name must be a string.

9️⃣ Modify Existing Collection Schema (collMod)

MongoDB Shell
NoSQL
Database
1db.runCommand({
2 collMod: "students",
3 validator: {
4 $jsonSchema: {
5 required: ["name", "age"],
6 properties: {
7 name: {
8 bsonType: "string",
9 description: "Name must be a string and is required"
10 }
11 }
12 }
13 }
14});
Query Result
JSON Output
✅ Schema for "students" collection successfully updated using collMod.

🔟 Create and Validate 'personal' Collection

MongoDB Shell
NoSQL
Database
1db.runCommand({
2 collMod: "personal",
3 validator: {
4 $jsonSchema: {
5 required: ["name", "age", "married", "dob", "weight", "kids", "address"],
6 properties: {
7 name: { bsonType: "string" },
8 age: { bsonType: "int", minimum: 20, maximum: 35 },
9 married: { bsonType: "bool" },
10 dob: { bsonType: "date" },
11 weight: { bsonType: "double" },
12 kids: { bsonType: "int" },
13 hobbies: { bsonType: "array", items: { bsonType: "string" } },
14 address: {
15 bsonType: "object",
16 required: ["street", "city", "zip"],
17 properties: {
18 street: { bsonType: "string" },
19 city: { bsonType: "string" },
20 zip: { bsonType: "int" }
21 }
22 }
23 }
24 }
25 }
26});
Query Result
JSON Output
✅ 'personal' collection updated with comprehensive validation rules including nested object and array checks.

1️⃣1️⃣ Valid Insert in 'personal' Collection

MongoDB Shell
NoSQL
Database
1db.personal.insertOne({
2 name: "Yash Hitesh",
3 age: 22,
4 married: true,
5 dob: ISODate("2001-10-01T07:30:00.000Z"),
6 weight: 61.22,
7 kids: 2,
8 hobbies: ["music", "travel"],
9 address: { street: "456 Main St", city: "Goa", zip: 10001 }
10});
Query Result
JSON Output
{
acknowledged: true,
insertedId: ObjectId('67c16f10ffc5a23fa2cb0ce2')
}

1️⃣2️⃣ Invalid Insert – Multiple Validation Errors

MongoDB Shell
NoSQL
Database
1db.personal.insertOne({
2 name: 23333,
3 age: 22,
4 married: "yes",
5 dob: ISODate("2001-10-01T07:30:00.000Z"),
6 weight: 61.22,
7 kids: 2,
8 hobbies: ["music", "travel"],
9 address: { street: "456 Main St", city: "Goa", zip: 10001 }
10});
Query Result
JSON Output
❌ MongoServerError: Document failed validation
{
propertyName: "name",
description: "Name must be a string and is required."
},
{
propertyName: "married",
description: "Married must be a boolean (true/false)."
}
Keep Going!MongoDB - Update & Replace Document