Dynamic Schemas & Schema Validation

Dynamic Schemas & Schema Validation in NoSQL Databases: A common misconception is that NoSQL databases lack schemas.

A common misconception is that NoSQL databases lack schemas. In reality, MongoDB offers Dynamic Schemas: the schema is enforced by the application layer and database-level validation rules, rather than static database tables.


1. Enforcing Schema Rules with JSON Schema Validation

You can instruct MongoDB to reject documents that do not match strict structural and typing constraints using the $jsonSchema validator:

// Create a collection with strict database-level schema validation
db.createCollection("students", {
  validator: {
    $jsonSchema: {
      bsonType: "object",
      required: ["name", "email", "gpa", "enrolled_courses"],
      properties: {
        name: {
          bsonType: "string",
          description: "Student full name must be a string."
        },
        email: {
          bsonType: "string",
          pattern: "^.+@.+\..+$",
          description: "Must be a valid email address format."
        },
        gpa: {
          bsonType: "double",
          minimum: 0.0,
          maximum: 4.0,
          description: "GPA must be a floating point number between 0.0 and 4.0."
        },
        enrolled_courses: {
          bsonType: "array",
          minItems: 1,
          items: {
            bsonType: "string"
          },
          description: "Must be an array of course codes with at least one entry."
        }
      }
    }
  },
  validationAction: "error", // Reject invalid writes with an error
  validationLevel: "strict"
});

2. Schema Evolution Across Versions

Unlike relational databases where migrating schemas requires blocking ALTER TABLE statements on multi-million row tables, MongoDB supports the Document Versioning Pattern:

// Version 1 Document (Historical users)
{
  "_id": ObjectId("..."),
  "schema_version": 1,
  "fullName": "Jane Doe"
}

// Version 2 Document (New users with separate name fields)
{
  "_id": ObjectId("..."),
  "schema_version": 2,
  "firstName": "Jane",
  "lastName": "Doe"
}

Your backend application handles the transition smoothly:

function getDisplayName(user) {
  if (user.schema_version === 2) {
    return `${user.firstName} ${user.lastName}`;
  }
  return user.fullName;
}