liveBook · Manning

Schema validation

As explained in MongoDB 8.0 in Action, Third Edition

Schema validation is a collection-level MongoDB feature that constrains documents to specified structural and value rules.

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

How MongoDB 8.0 in Action, Third Edition covers it

How deep it goes
Descends through JSON Schema configuration, enforcement levels, actions, permissions, and failed-operation diagnostics.
Examples
Uses users, flight routes, airports, and an invalid routes insert to demonstrate type, pattern, range, and code validation.
What it assumes
Assumes MongoDB collection and document basics while teaching JSON Schema rules, validator commands, permissions, and enforcement behavior.
What you can do after
Apply it via MongoDB validators to enforce document rules, stage adoption, diagnose violations, or deliberately bypass checks when necessary.
How it connects
Connects JSON Schema with collection design, data migration, validation levels, and MongoDB application access.

Also explained in

Compare how 7 books explain schema validation →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of MongoDB 8.0 in Action, Third Edition. The section links point to the parts of the book it draws on.