What is schema validation in MongoDB?

BeginnerConceptMongoDB
Answer

Short answer

Although MongoDB is schema-flexible, you can attach a JSON Schema validator to a collection so inserts and updates must match rules — required fields, types, allowed values. It gives you guard rails without losing flexibility.

Example

db.createCollection("orders", {
  validator: {
    $jsonSchema: {
      bsonType: "object",
      required: ["customerId", "total", "status"],
      properties: {
        customerId: { bsonType: "objectId" },
        total: { bsonType: ["double", "decimal", "int"], minimum: 0 },
        status: { enum: ["NEW", "PROCESSING", "SHIPPED", "CANCELLED"] }
      }
    }
  },
  validationAction: "error"          // or "warn" to only log
})

db.orders.insertOne({ total: -5 })   // ❌ Document failed validation

Add validation to an existing collection with collMod.

What to say in the interview

"MongoDB supports $jsonSchema validators per collection to enforce required fields, types and enums, with error or warn actions. It's a good balance — flexible documents with guard rails against bad data."

All Databases (MySQL, PostgreSQL, MongoDB) questions Roadmap: MongoDB basics

More on MongoDB