← Back to MongoDB Course | Chapter 2: CRUD — Create | Lesson 6 of 7

Validation basics

Schema validation lets you require fields and types even though MongoDB is flexible.

In this page:

  1. Validation basics
Syntax
javascript
db.createCollection("collection_name", {
  validator: {
    $jsonSchema: {
      bsonType: "object",
      required: ["field1"],
      properties: { field1: { bsonType: "string" } }
    }
  }
})

Validation basics

When creating a collection, add a validator using $jsonSchema to demand required fields, types and value ranges. validationAction chooses whether invalid writes are rejected (error) or only logged (warn).

Existing documents are not re-checked until they are updated.

Note: Start with validationAction warn to see what would fail before enforcing.

Example: Validation basics

bash
test> db.createCollection("accounts", {
...   validator: { $jsonSchema: {
...     bsonType: "object",
...     required: ["email", "age"],
...     properties: {
...       email: { bsonType: "string" },
...       age: { bsonType: "int", minimum: 18 }
...     }
...   } }
... })
{ ok: 1 }
test> db.accounts.insertOne({ email: "[email protected]", age: 15 })
MongoServerError: Document failed validation
test> db.accounts.insertOne({ email: "[email protected]", age: 30 })
{ acknowledged: true, insertedId: ObjectId('65a1b2c3d4e5f60718293a4e') }

⚠️ Run this in your own terminal or Node.js environment.

Related Topics
Common Mistakes
  1. Assuming MongoDB always enforces a schema
  2. Forgetting validation only applies on writes
  3. Making validators too strict for real data
Chapter Summary
  • $jsonSchema defines required fields and types
  • validationAction is error or warn
  • Set at collection creation or with collMod
  • Checked on inserts and updates
🔒

Chapter Quiz — Complete all 7 topics to unlock

0/7 topics done

Complete these topics first:

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.