Skip to main content

Archive

Show more

MongoDB Data Validation

MongoDB: Data Validation

  • Data validation in MongoDB ensures that the data stored in your database meets certain requirements and constraints.
  • This tutorial will cover various scenarios and methods for implementing data validation in MongoDB.

1. Validation Rules

MongoDB allows you to define validation rules at the collection level using JSON Schema.

Validation Criteria:

  • Required Fields: Ensure that certain fields are present in all documents.
  • Data Types: Define the expected data types for fields.
  • Range Constraints: Specify minimum and maximum values for numeric fields.
  • Pattern Matching: Validate string fields based on regular expressions.
  • Custom Validation: Implement custom validation logic using JavaScript functions.

2. Defining Validation Rules

To define validation rules for a collection, you can use the collMod command in the MongoDB shell.

Steps to Define Validation:

  1. Ensure you are connected to the MongoDB database using mongosh.
  2. Run the following command to define validation rules for a collection:
db.createCollection("collection_name", {
  validator: {
    $jsonSchema: {
      // Define validation rules here
    }
  }
})

Replace collection_name with the name of your collection and define the validation rules within the JSON schema.


3. Example Validation Rules

Here's an example of defining validation rules for a collection:

db.createCollection("users", {
  validator: {
    $jsonSchema: {
      bsonType: "object",
      required: ["username", "email"],
      properties: {
        username: {
          bsonType: "string",
          description: "Username must be a string and is required."
        },
        email: {
          bsonType: "string",
          pattern: "^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\\.[a-zA-Z]{2,}$",
          description: "Email must be a valid email address and is required."
        }
      }
    }
  }
})

In this example, we ensure that the username and email fields are present in all documents, and their values match the specified criteria.


4. What's Next?

Now that you've learned how to implement data validation in MongoDB, you can ensure data integrity and consistency in your database.

Explore more advanced validation techniques and best practices to further enhance the quality and reliability of your MongoDB data.

Comments