MongoDB Schema Validation: Rules
MongoDB Schema Validation: Rules
MongoDB Schema Validation: Rules
Tip: JSON Schema Validation
DB::command([
'collMod' => 'posts',
'validator' => [
'$jsonSchema' => [
'bsonType' => 'object',
'required' => ['title', 'content'],
'properties' => [
'title' => ['bsonType' => 'string'],
'views' => ['bsonType' => 'int', 'minimum' => 0],
],
],
],
]);
Gotcha: Validation Level
strict(default) — validates all inserts and updatesmoderate— only validates existing documents that are modified
Tip: Allow Additional Fields
'additionalProperties' => true,
Allows fields not defined in the schema. Set to false for strict schemas.
Gotcha: Validation Action
'validationAction' => 'warn', // or 'error'
warn logs violations but allows the write. error rejects it.
Tip: Array Validation
'tags' => [
'bsonType' => 'array',
'items' => ['bsonType' => 'string'],
],
Ensures tags is an array of strings.
Gotcha: Enum Validation
'status' => [
'bsonType' => 'string',
'enum' => ['draft', 'published', 'archived'],
],
Tip: Embed or Reference? The 80/20 Rule
If you always access data together, embed it. If you access it independently, reference it. The 16MB document size limit is the hard boundary — stay under 1MB for most documents.
Tip: Index Your Query Patterns, Not All Fields
Creating indexes on every field wastes RAM. Use explain() to find in-memory sorts and collection scans. Index only what your actual queries filter on.
Gotcha: No Transaction Rollback for Index Builds
Building an index on a large collection can take hours. If it fails midway, the partial index is silently discarded. Plan index builds during maintenance windows.
Senior Insight
MongoDB's schema validation with $jsonSchema (3.6+) addresses MongoDB's schema-less reputation. I use it to enforce document structure at the database level, catching malformed documents before they enter the collection. The validation rules support required fields, data types, enum values, and even custom validation expressions. Combine schema validation with application-level validation for defense in depth. The validation only applies to new writes — existing documents are not re-validated.
Source: MongoDB Developer Center (https://www.mongodb.com/developer/), MongoDB Engineering Blog (https://www.mongodb.com/blog/channel/engineering-blog), Studio 3T Blog (https://studio3t.com/blog/)