Validating Document Schema

1. Creating Schema Validation Rules

AspectDetail
WhereAt 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

KeywordDescription
bsonTypeSpecific BSON type (preferred over type)
requiredArray of required field names
propertiesPer-field schemas
additionalPropertiesAllow undeclared fields?
enumAllowed values
minimum / maximumNumber bounds
minLength / maxLength / patternString constraints
minItems / maxItems / uniqueItemsArray constraints

3. Setting Validation Level

LevelBehavior
strict (default)Validate all inserts and updates
moderateOnly validate inserts and updates on docs that already match the validator
offNo validation

4. Setting Validation Action

ActionBehavior
error (default)Reject write
warnAllow write; log warning

5. Using Query Expression Validation

AspectDetail
FormPlain query operators (no $jsonSchema)
UseComplex rules using $expr, $regex
{ validator: { $expr: { $gt: ["$endDate", "$startDate"] } } }

6. Validating Required Fields

FormEffect
required: ["a","b"]Fields must be present
Null allowed?Yes unless bsonType excludes null

7. Validating Data Types

FormEffect
bsonType: "int"Strict Int32 only
bsonType: ["int","long"]Either
bsonType: "number"Any numeric

8. Setting Min/Max Values

KeywordEffect
minimum / maximumInclusive numeric bounds
exclusiveMinimum / exclusiveMaximumExclusive bounds (bool flag in 4.0+; numeric in 5.0+)

9. Using Pattern Matching

FormEffect
pattern: "^[a-z]+$"PCRE regex
CombinedWith minLength/maxLength

10. Validating Array Items

KeywordEffect
items: schemaEach element matches schema
items: [schemas]Positional schemas
minItems / maxItemsBounds
uniqueItemsNo duplicate values

11. Updating Validation Rules

CommandEffect
collMod with validatorReplace existing rules
AtomicExisting docs not re-validated
db.runCommand({ collMod: "users", validator: { $jsonSchema: {...} }, validationLevel: "moderate" });

12. Bypassing Validation

OptionEffect
bypassDocumentValidation: trueSkip validation (write op flag)
Required rolebypassDocumentValidation privilege
Use caseMigrations, repairs