Catalog My learning Blog
MongoDB Tutorial: Schema Design, Indexing and Sharding · Phase 1 · Lesson 5 · 3 min read

MongoDB Data Types and Schema Validation

On this page
  1. Why a flexible schema drifts
  2. Choosing BSON types for common fields
  3. Schema validation with $jsonSchema
  4. Adding validation to an existing collection
  5. What validation doesn't replace
  6. Check yourself

Why a flexible schema drifts

A customers collection, three services writing to it. Two years later: email and Email both exist, createdAt is sometimes a date and sometimes a string, credit is sometimes a number and sometimes "10.50". Every reader has defensive code, and reports are subtly wrong. Nothing forced the shape, so it drifted.

Choosing BSON types for common fields

FieldTypeNot
TimestampsDateStrings like "10/10/2026"
MoneyDecimal128 (or integer cents)Doubles (Day 3)
Counts and quantitiesInt32 / Int64Strings
Status valuesString from a fixed setFree text
IDs from other systemsString (keeps leading zeros)Number
FlagsBoolean"yes" / "no"

Schema validation with $jsonSchema

Attach a validator when creating a collection (or later with collMod):

Code
db.createCollection("customers", {
  validator: {
    $jsonSchema: {
      bsonType: "object",
      required: ["email", "createdAt"],
      properties: {
        email:     { bsonType: "string", pattern: "^.+@.+$" },
        createdAt: { bsonType: "date" },
        plan:      { enum: ["starter", "pro", "enterprise"] },
        credit:    { bsonType: "decimal", minimum: 0 }
      }
    }
  }
})

A conforming insert succeeds. Tested on MongoDB 9, an insert with createdAt as the string "2026-10-10" fails:

Code
MongoServerError: Document failed validation

The full error includes errInfo details naming the failing rule (here, createdAt has the wrong type), which makes debugging straightforward.

A validator checks each insert and update against a JSON Schema; validationLevel decides which documents are checked and validationAction whether to reject or warn.
A validator checks each insert and update against a JSON Schema; validationLevel decides which documents are checked and validationAction whether to reject or warn.

Adding validation to an existing collection

Old data probably doesn't conform yet. Two settings let you introduce rules gradually:

SettingValuesEffect
validationLevelstrict (default)Check every insert and update
moderateCheck inserts, and updates to documents that already pass; leave non-conforming existing documents alone
validationActionerror (default)Reject invalid writes
warnAllow them, but log a warning
validationLevel (MongoDB 9.0)constraintLike strict, and guarantees every existing document passes too

A safe rollout:

  1. Add the validator with validationAction: "warn" and watch the logs: what's still writing bad data?
  2. Fix those writers; clean up existing data (find it with $nor: [ <schema> ] or $type queries).
  3. Switch to validationLevel: "moderate", validationAction: "error", then to strict once old data is clean.
  4. On MongoDB 9.0, optionally finish with constraint, which guarantees every document in the collection, old ones included, satisfies the validator.

Enabling constraint on an existing collection is a two-step collMod: first prepareConstraintValidationLevel: true, then validationLevel: "constraint" with validationAction: "error". The second step scans every document and fails if any breaks the rules, so it doubles as a final check. While it's on, the validator can't be edited; drop back to strict to change the rules (MongoDB docs).

JavaScript
db.runCommand({ collMod: "customers", validator: { $jsonSchema: { /* ... */ } },
                validationLevel: "moderate", validationAction: "warn" })

What validation doesn't replace

Validation checks the shape of a single document. It can't check business rules across documents ("an order's customer must exist", "credit can't exceed the plan's limit"), and the error messages aren't meant for end users. Keep input validation and business rules in the application; use schema validation as the database's last line of defense against bad writes from any source, including scripts and future services.

Many teams also use an ODM or schema library in code (Mongoose in Node, Pydantic models, C# classes with the driver's serialization, or the MongoDB provider for Entity Framework Core, which lets .NET teams use a DbContext and LINQ against MongoDB) so the application's types and the database validator describe the same shape.

Check yourself

Many services and scripts write to the same collections, and without rules, types and shapes drift: a price stored as a string here, a missing field there. Validation rejects bad writes at the database, while the application still relies on a consistent shape to work.

Start with validationAction: "warn" (and validationLevel: "moderate"), find and fix bad writers and data, then switch to error and strict.

No. Validators check a single document's shape and values against rules; they can't look up other documents. Rules that span documents, like referential integrity, belong in the application, or are enforced inside a transaction.

strict validates every insert and update. moderate validates inserts and updates to documents that already pass, but lets updates to existing invalid documents through, which helps while cleaning up old data.

Query with the same $jsonSchema inside $nor, for example db.orders.find({ $nor: [{ $jsonSchema: schema }] }), to list the non-conforming documents before enforcing it.