Lesson 29 of 50 – Schema Validation in MongoDB
58%

Schema Validation in MongoDB

Schema validation helps control the structure and data types of documents stored in a MongoDB collection. It can prevent invalid data, such as a student's age being stored as text or a required field being missing.

1. What Is Schema Validation?

MongoDB has a flexible schema by default. Documents in the same collection can contain different fields. Schema validation allows you to define rules that documents must follow when they are inserted or updated.

For example, a student document might require:

  • name must be a string.
  • age must be a number.
  • course must be a string.
  • fees must be a non-negative number.

Without validation, an application might insert:

{
    name: 12345,
    age: "twenty",
    course: true,
    fees: "five thousand"
}

These values may not match the structure expected by the application. Schema validation helps prevent such inconsistencies.

2. Create a Collection with Validation

Use db.createCollection() with the validator option to define validation rules.

use school

db.createCollection("validated_students", {
    validator: {
        $jsonSchema: {
            bsonType: "object",
            required: ["name", "age", "course"],
            properties: {
                name: {
                    bsonType: "string",
                    description: "Name must be a string"
                },
                age: {
                    bsonType: "int",
                    minimum: 1,
                    maximum: 100,
                    description: "Age must be an integer from 1 to 100"
                },
                course: {
                    bsonType: "string",
                    description: "Course must be a string"
                }
            }
        }
    }
})

Understand the important options:

  • validator defines the validation rules.
  • $jsonSchema specifies a JSON Schema-style validator.
  • bsonType specifies the required BSON data type.
  • required lists fields that must be present.
  • minimum and maximum define numeric boundaries.

Note: Run the collection creation command only once. If the collection already exists, use collMod to modify its validator instead.

3. Insert Valid Documents

A document that satisfies the validation rules can be inserted successfully.

db.validated_students.insertOne({
    name: "Rahul",
    age: 20,
    course: "Java"
})

Another valid example:

db.validated_students.insertOne({
    name: "Priya",
    age: 22,
    course: "Python"
})

Both documents contain the required fields and use the expected data types. MongoDB also generates an _id field automatically when one is not provided.

4. Test Invalid Data Types

Try inserting a document where the age is a string instead of an integer.

db.validated_students.insertOne({
    name: "Aman",
    age: "twenty",
    course: "Java"
})

With the default validationAction: "error", MongoDB rejects this insert because age does not have BSON type int.

Another invalid example:

db.validated_students.insertOne({
    name: "Neha",
    age: 19
})

This document is rejected because the required course field is missing.

Important: In MongoDB, a JavaScript integer such as 20 is normally stored as BSON int when it fits the 32-bit integer range. Decimal values such as 20.5 are generally stored as BSON double.

5. Use minimum and maximum Rules

Numeric validation rules can restrict the acceptable range of a value.

db.runCommand({
    collMod: "validated_students",
    validator: {
        $jsonSchema: {
            bsonType: "object",
            required: ["name", "age", "course"],
            properties: {
                name: {
                    bsonType: "string"
                },
                age: {
                    bsonType: "int",
                    minimum: 18,
                    maximum: 60
                },
                course: {
                    bsonType: "string"
                }
            }
        }
    },
    validationLevel: "strict",
    validationAction: "error"
})

This changes the validator so that the age must be an integer between 18 and 60, inclusive.

The command uses collMod because the collection already exists. It replaces the previous validator with the new one.

After this change, try inserting an age of 17 or 65. Both should be rejected.

6. Use enum to Restrict Allowed Values

The enum keyword restricts a field to a predefined list of values.

db.runCommand({
    collMod: "validated_students",
    validator: {
        $jsonSchema: {
            bsonType: "object",
            required: ["name", "age", "course"],
            properties: {
                name: {
                    bsonType: "string"
                },
                age: {
                    bsonType: "int",
                    minimum: 18,
                    maximum: 60
                },
                course: {
                    bsonType: "string",
                    enum: ["Java", "Python", "Web Development"]
                }
            }
        }
    }
})

With this validator, the course must be one of Java, Python, or Web Development.

Example of a valid document:

db.validated_students.insertOne({
    name: "Ravi",
    age: 25,
    course: "Java"
})

Example of an invalid document:

db.validated_students.insertOne({
    name: "Kiran",
    age: 25,
    course: "Accounting"
})

The second document is rejected because Accounting is not in the allowed list.

7. validationLevel

The validationLevel option determines which inserts and updates are checked against the collection's validator.

Strict

"strict" applies validation to all inserts and updates.

Moderate

"moderate" applies validation to inserts and updates of documents that already satisfy the validator. Updates to existing invalid documents are not necessarily required to make those documents valid.

db.runCommand({
    collMod: "validated_students",
    validationLevel: "strict"
})

Use strict validation when the collection should consistently follow the defined rules.

8. validationAction

The validationAction option determines what MongoDB does when a document violates the validator.

Error

"error" rejects the invalid insert or update. This is the default behavior.

Warn

"warn" allows the operation but logs a validation warning.

db.runCommand({
    collMod: "validated_students",
    validationAction: "warn"
})

Warning mode can be useful when introducing validation to an existing collection. However, invalid documents can still be written in this mode.

Best practice: Use error mode for important data rules unless you deliberately need warning-only behavior.

9. View Collection Validation Rules

You can inspect collection information to review its validator and other options.

db.getCollectionInfos({
    name: "validated_students"
})

The result includes the collection's options, including its validator when one is configured.

To check whether the documents currently in the collection follow the intended rules, test your validation behavior with valid and invalid inserts and updates. Adding a validator does not automatically repair existing invalid documents.

10. Validate Updates

Schema validation applies to updates as well as inserts. With strict validation and error mode, an update that would leave a document invalid is rejected.

First, insert a valid document:

db.validated_students.insertOne({
    name: "Suman",
    age: 24,
    course: "Python"
})

Now try setting age to an invalid string:

db.validated_students.updateOne(
    { name: "Suman" },
    { $set: { age: "twenty-four" } }
)

If the collection uses strict validation with validationAction: "error", MongoDB rejects this update because the age would no longer be an integer.

Update the age with a valid integer instead:

db.validated_students.updateOne(
    { name: "Suman" },
    { $set: { age: 25 } }
)

This update succeeds if the document satisfies all the other active validation rules.

11. Practical Assignment

Create a validated collection for a student management system.

  1. Create a collection named assignment_students.
  2. Make name, age, and course required fields.
  3. Require name and course to be strings.
  4. Require age to be an integer between 18 and 60.
  5. Allow only Java, Python, and Web Development as course values.
  6. Insert a valid student document.
  7. Try inserting a document without a course field.
  8. Try inserting a student with an invalid age type.
  9. Change the validation action to warning mode and observe the behavior.
  10. Use db.getCollectionInfos() to inspect the collection options.

🧠 Quick Quiz

1. What is the purpose of schema validation?




2. What does validationAction: "error" do when a document violates the validator?




3. Which option lists fields that must be present?