| Keyword | Purpose |
|---|---|
bsonType | Specifies the BSON data type (string, int, bool, date, array, object, etc.) |
required | Lists mandatory fields |
properties | Defines validation rules for each field |
minimum / maximum | Numeric range validation |
minLength / maxLength | String length validation |
pattern | Validates strings using a regular expression |
enum | Restricts a field to specific values |
Example:
db.createCollection("products", {
validator: {
$jsonSchema: {
bsonType: "object",
required: ["name", "price", "category"],
properties: {
name: {
bsonType: "string",
minLength: 3
},
price: {
bsonType: "double",
minimum: 0
},
category: {
enum: ["Electronics", "Clothing", "Books"]
},
inStock: {
bsonType: "bool"
}
}
}
}
});Add in Existing Collection
db.runCommand({
collMod: "employees",
validator: {
$jsonSchema: {
bsonType: "object",
required: ["name", "age", "department"],
properties: {
name: {
bsonType: "string"
},
age: {
bsonType: "int",
minimum: 18
},
department: {
bsonType: "string"
}
}
}
},
validationLevel: "strict",
validationAction: "error"
});