⬅ Previous Topic
MongoDB Schema Validation with JSON SchemaNext Topic ⮕
MongoDB with Python using PyMongo⬅ Previous Topic
MongoDB Schema Validation with JSON SchemaNext Topic ⮕
MongoDB with Python using PyMongoIn MongoDB, even though schemas are flexible, you can still define validation rules to ensure data quality and consistency using JSON Schema validation.
This is useful when you want to allow flexibility, but still enforce structure—like requiring a field to be a string, or restricting values to a specific set.
MongoDB’s dynamic schema is powerful, but with great power comes the possibility of bad data. Validation allows you to:
name
or email
are always presentMongoDB lets you define validation rules using JSON Schema when creating or updating a collection.
Let’s create a students
collection where:
name
is a required stringage
is a required number
db.createCollection("students", {
validator: {
$jsonSchema: {
bsonType: "object",
required: ["name", "age"],
properties: {
name: {
bsonType: "string",
description: "must be a string and is required"
},
age: {
bsonType: "int",
minimum: 0,
description: "must be an integer ≥ 0 and is required"
}
}
}
}
});
{ ok: 1 }
Explanation: The schema requires both name
and age
. The age must be an integer and not negative. Any document violating this will be rejected.
db.students.insertOne({ name: "Asha", age: 20 });
{ acknowledged: true, insertedId: ObjectId("...") }
db.students.insertOne({ name: "Ravi", age: "twenty" });
WriteError: Document failed validation
Why does MongoDB reject the second document?
Answer: Because the age
is a string ("twenty") and not an integer as required by the validation rule.
Let’s now allow only specific values for a status
field (e.g., “active”, “inactive”, “pending”).
db.createCollection("accounts", {
validator: {
$jsonSchema: {
bsonType: "object",
required: ["username", "status"],
properties: {
username: {
bsonType: "string",
description: "must be a string and is required"
},
status: {
enum: ["active", "inactive", "pending"],
description: "can only be one of the enum values"
}
}
}
}
});
Try a Valid Insert:
db.accounts.insertOne({ username: "john_doe", status: "active" });
{ acknowledged: true, insertedId: ObjectId("...") }
Try an Invalid Insert:
db.accounts.insertOne({ username: "jane_doe", status: "banned" });
WriteError: Document failed validation
Let’s say you want to allow an optional email
field, but if it exists, it must be a string:
db.createCollection("employees", {
validator: {
$jsonSchema: {
bsonType: "object",
required: ["name"],
properties: {
name: {
bsonType: "string"
},
email: {
bsonType: "string"
}
}
}
}
});
Explanation: Here, email
is not required but still validated if provided. This is useful for optional fields.
db.getCollectionInfos({ name: "students" })
db.runCommand({
collMod: "students",
validator: {
$jsonSchema: {
bsonType: "object",
required: ["name", "age"],
properties: {
name: { bsonType: "string" },
age: { bsonType: "int", minimum: 0 }
}
}
}
});
Validation rules in MongoDB allow you to enforce a structure within your flexible schema. You can require fields, set type restrictions, limit values, and even define nested document structure. This helps ensure the data inserted into collections is meaningful and consistent.
Now that you know how to define custom validation rules, you’re ready to build MongoDB collections that are both powerful and safe from invalid data.
⬅ Previous Topic
MongoDB Schema Validation with JSON SchemaNext Topic ⮕
MongoDB with Python using PyMongoYou can support this website with a contribution of your choice.
When making a contribution, mention your name, and programguru.org in the message. Your name shall be displayed in the sponsors list.