Validating Document Schema
1. Creating Schema Validation Rules
| Aspect | Detail |
|---|---|
| Where | At createCollection or via collMod |
| Form | $jsonSchema or query expression |
db.createCollection("users", {
validator: { $jsonSchema: {
bsonType: "object",
required: ["email", "createdAt"],
properties: {
email: { bsonType: "string", pattern: "^.+@.+$" },
age: { bsonType: "int", minimum: 0, maximum: 150 },
createdAt: { bsonType: "date" }
}
} }
});
2. Using JSON Schema Validation
| Keyword | Description |
|---|---|
| bsonType | Specific BSON type (preferred over type) |
| required | Array of required field names |
| properties | Per-field schemas |
| additionalProperties | Allow undeclared fields? |
| enum | Allowed values |
| minimum / maximum | Number bounds |
| minLength / maxLength / pattern | String constraints |
| minItems / maxItems / uniqueItems | Array constraints |
3. Setting Validation Level
| Level | Behavior |
|---|---|
| strict (default) | Validate all inserts and updates |
| moderate | Only validate inserts and updates on docs that already match the validator |
| off | No validation |
4. Setting Validation Action
| Action | Behavior |
|---|---|
| error (default) | Reject write |
| warn | Allow write; log warning |
5. Using Query Expression Validation
| Aspect | Detail |
|---|---|
| Form | Plain query operators (no $jsonSchema) |
| Use | Complex rules using $expr, $regex |
{ validator: { $expr: { $gt: ["$endDate", "$startDate"] } } }
6. Validating Required Fields
| Form | Effect |
|---|---|
required: ["a","b"] | Fields must be present |
| Null allowed? | Yes unless bsonType excludes null |
7. Validating Data Types
| Form | Effect |
|---|---|
bsonType: "int" | Strict Int32 only |
bsonType: ["int","long"] | Either |
bsonType: "number" | Any numeric |
8. Setting Min/Max Values
| Keyword | Effect |
|---|---|
| minimum / maximum | Inclusive numeric bounds |
| exclusiveMinimum / exclusiveMaximum | Exclusive bounds (bool flag in 4.0+; numeric in 5.0+) |
9. Using Pattern Matching
| Form | Effect |
|---|---|
pattern: "^[a-z]+$" | PCRE regex |
| Combined | With minLength/maxLength |
10. Validating Array Items
| Keyword | Effect |
|---|---|
| items: schema | Each element matches schema |
| items: [schemas] | Positional schemas |
| minItems / maxItems | Bounds |
| uniqueItems | No duplicate values |
11. Updating Validation Rules
| Command | Effect |
|---|---|
| collMod with validator | Replace existing rules |
| Atomic | Existing docs not re-validated |
db.runCommand({ collMod: "users", validator: { $jsonSchema: {...} }, validationLevel: "moderate" });
12. Bypassing Validation
| Option | Effect |
|---|---|
| bypassDocumentValidation: true | Skip validation (write op flag) |
| Required role | bypassDocumentValidation privilege |
| Use case | Migrations, repairs |