Perform simple validation in MongoDB?

For validation in MongoDB, use validator with $jsonSchema to enforce document structure and data types. Validation rules are applied when creating or updating documents.

Syntax

db.createCollection("collectionName", {
    validator: { 
        $jsonSchema: {
            bsonType: "object",
            required: ["field1", "field2"],
            properties: {
                field1: {
                    bsonType: "string",
                    description: "Field description"
                }
            }
        }
    }
});

Example: Create Collection with Validation

db.createCollection("demo437", {
    validator: { 
        $jsonSchema: {
            bsonType: "object",
            required: ["FirstName", "LastName"],
            properties: {
                FirstName: {
                    bsonType: "string",
                    description: "This is required"
                },
                LastName: {
                    bsonType: "string",
                    description: "This is required"
                }
            }
        }
    }
});
{ "ok" : 1 }

Testing Validation Rules

Invalid Insert (Wrong Data Type)

db.demo437.insertOne({"FirstName":"John","LastName":1234});
WriteError: Document failed validation
{
    "index" : 0,
    "code" : 121,
    "errmsg" : "Document failed validation",
    "op" : {
        "_id" : ObjectId("5e7757ebbbc41e36cc3cae9a"),
        "FirstName" : "John",
        "LastName" : 1234
    }
}

Valid Insert

db.demo437.insertOne({"FirstName":"John","LastName":"Smith"});
{
    "acknowledged" : true,
    "insertedId" : ObjectId("5e7757f7bbc41e36cc3cae9b")
}

Another Invalid Insert

db.demo437.insertOne({"FirstName":9887,"LastName":"Miller"});
WriteError: Document failed validation

Another Valid Insert

db.demo437.insertOne({"FirstName":"David","LastName":"Miller"});
{
    "acknowledged" : true,
    "insertedId" : ObjectId("5e775816bbc41e36cc3cae9d")
}

Verify Results

db.demo437.find();
{ "_id" : ObjectId("5e7757f7bbc41e36cc3cae9b"), "FirstName" : "John", "LastName" : "Smith" }
{ "_id" : ObjectId("5e775816bbc41e36cc3cae9d"), "FirstName" : "David", "LastName" : "Miller" }

Conclusion

MongoDB validation using $jsonSchema enforces data integrity by rejecting documents that don't match the defined schema. Only valid documents that satisfy the required fields and data types are successfully inserted.

Updated on: 2026-03-15T02:59:12+05:30

318 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements