MongoDB Data Types and Schema Validation
On this page
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
| Field | Type | Not |
|---|---|---|
| Timestamps | Date | Strings like "10/10/2026" |
| Money | Decimal128 (or integer cents) | Doubles (Day 3) |
| Counts and quantities | Int32 / Int64 | Strings |
| Status values | String from a fixed set | Free text |
| IDs from other systems | String (keeps leading zeros) | Number |
| Flags | Boolean | "yes" / "no" |
Schema validation with $jsonSchema
Attach a validator when creating a collection (or later with collMod):
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:
MongoServerError: Document failed validationThe full error includes errInfo details naming the failing rule (here, createdAt has the wrong type), which makes debugging straightforward.
Adding validation to an existing collection
Old data probably doesn't conform yet. Two settings let you introduce rules gradually:
| Setting | Values | Effect |
|---|---|---|
validationLevel | strict (default) | Check every insert and update |
moderate | Check inserts, and updates to documents that already pass; leave non-conforming existing documents alone | |
validationAction | error (default) | Reject invalid writes |
warn | Allow them, but log a warning | |
validationLevel (MongoDB 9.0) | constraint | Like strict, and guarantees every existing document passes too |
A safe rollout:
- Add the validator with
validationAction: "warn"and watch the logs: what's still writing bad data? - Fix those writers; clean up existing data (find it with
$nor: [ <schema> ]or$typequeries). - Switch to
validationLevel: "moderate",validationAction: "error", then tostrictonce old data is clean. - 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).
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.