JSON Schema Validation in Mongo db

 JSON Schema validation in MongoDB enables developers to enforce data consistency and integrity at the database level. This feature is supported by MongoDB collections through schema validation rules, defined as part of a collection's options when creating or updating it. These rules are based on a subset of the JSON Schema standard.

Setting Up JSON Schema Validation

  1. Define a JSON Schema: Specify the schema rules for the data structure, including required fields, types, and custom validation logic.

  2. Apply the Schema to a Collection: Use the validator option when creating a collection or modifying it with the collMod command.

Steps to Implement JSON Schema Validation

1. Create a Collection with Validation

db.createCollection("products", {
        validator: {
          $jsonSchema: {
            bsonType: "object",
            required: ["name", "price", "category"],
            properties: {
              name: {
                bsonType: "string",
                description: "must be a string and is required",
              },
              price: {
                bsonType: "double",
                minimum: 0,
                description: "must be a non-negative number and is required",
              },
              category: {
                bsonType: "string",
                description: "must be a string and is required",
              },
              tags: {
                bsonType: "array",
                items: {
                  bsonType: "string",
                },
                description: "must be an array of strings if provided",
              },
            },
          },
        },
      });

Key Features of MongoDB JSON Schema

  • bsonType vs type: Use bsonType for MongoDB's extended JSON types like objectId, date, and binData.
  • Logical Operators:
    • $and, $or, $not: Combine multiple validation rules.
  • Additional Validation:
    • Min/max for arrays, strings, and numbers.
    • Enum values for specific fields.
    • Regex patterns for strings.

Benefits of JSON Schema Validation

  • Improves Data Integrity: Enforces consistency in your data structure.
  • Eases Application Logic: Offloads validation logic to the database layer.
  • Scalable: Supports dynamic and complex schema requirements.