🔥Limited Offer: Get 50% OFFon AI & Full Stack Courses🔥
Back to MongoDB Notes
Topic #23

MongoDB Validation


Schema Validation

By default MongoDB has a flexible schema. This means that there is no strict schema validation set up initially.

Schema validation rules can be created in order to ensure that all documents in a collection share a similar structure.


Schema Validation

MongoDB supports JSON Schema validation. The $jsonSchema operator allows us to define our document structure.

Example

db.createCollection("posts", {
  validator: {
    $jsonSchema: {
      bsonType: "object",
      required: [ "title", "body" ],
      properties: {
        title: {
          bsonType: "string",
          description: "Title of post - Required."
        },
        body: {
          bsonType: "string",
          description: "Body of post - Required."
        },
        category: {
          bsonType: "string",
          description: "Category of post - Optional."
        },
        likes: {
          bsonType: "int",
          description: "Post like count. Must be an integer - Optional."
        },
        tags: {
          bsonType: ["string"],
          description: "Must be an array of strings - Optional."
        },
        date: {
          bsonType: "date",
          description: "Must be a date - Optional."
        }
      }
    }
  }
})

This will create the posts collection in the current database and specify the JSON Schema validation requirements for the collection.

Want to go beyond the notes?

Join CodingNow 2.0's MongoDB course — live mentorship, real projects, and 100% placement support.

Enroll Now — Free Demo Available

MongoDB Validation – FAQs

Quick answers about learning MongoDB Validation in MongoDB.

This free note from CodingNow 2.0 explains MongoDB Validation in MongoDB — concept, syntax and worked code examples you can copy, run and revise before interviews.
Yes. Every MongoDB topic on CodingNow 2.0, including MongoDB Validation, is 100% free with no signup required.
With focused practice, most students grasp MongoDB Validation in 1–3 days from these notes; pairing it with CodingNow 2.0's mentor-led course takes you to job-ready depth faster.
Use the code examples in this note, then ask doubts for free on the CodingNow 2.0 Community (/community) — expert instructors answer within 24 hours.
WhatsApp
Call NowEnroll Now