Schema validation constrains documents in a MongoDB collection with structural, type, pattern, and value rules. It preserves consistency without removing MongoDB’s flexible document model. section 2.6.1 section 5.4
Implement validation progressively:
- Define a JSON Schema containing required fields, BSON types, patterns, and numeric limits. section 5.4.1
- Apply the validator when creating a collection with db.createCollection(), or add it later with collMod. section 5.4.1
- Choose validationLevel moderate to enforce rules on new documents and compliant existing documents when updated. section 5.4.1
- Choose validationAction error to reject violations, or warn to allow them while logging warnings during migrations or gradual adoption. section 5.4.3
- Test invalid inserts and read the returned rule details before deploying stricter enforcement. section 5.4.2
Rejecting an invalid route
A routes validator can require flight_id, airline, src_airport, and dst_airport. An insert using flight_id "XYZ123" and airline.id -410 fails because the identifier pattern and positive-integer rule are violated; MongoDB returns the failed properties and descriptions. section 5.4.1 section 5.4.2
Listing 5.1 Example schema validator
db.runCommand({
collMod: "routes",
validator: {
$jsonSchema: {
bsonType: "object",
required: [
"flight_id",
"airline",
"src_airport",
"dst_airport"
],
properties: {
flight_id: {
bsonType: "string",
pattern: "^FL\\d+$",
description: "must be a string starting
➥with 'FL' followed by numbers"
},
airline: {
bsonType: "object",
properties: {
id: {
bsonType: "int",
minimum: 1,
description: "must be a positive integer"
}
}
},
src_airport: {
bsonType: "object",
properties: {
code: {
bsonType: "string",
description: "must be a valid airport code"
}
}
},
dst_airport: {
bsonType: "object",
properties: {
code: {
bsonType: "string",
description: "must be a valid airport code"
}
}
}
}
}
},
validationLevel: "moderate",
validationAction: "error"
})
Inspect the complete collMod validator for the routes collection, including required fields, nested properties, BSON types, and patterns. section 5.4.1






