Sling Academy
Home/MongoDB/How to create validation rules in MongoDB (with examples)

How to create validation rules in MongoDB (with examples)

Last updated: February 02, 2024

Introduction

MongoDB, a NoSQL database, offers flexibility in how data can be stored and managed. This flexibility, however, can lead to data inconsistencies if proper data validation rules are not in place. In this tutorial, we’ll explore how to create validation rules in MongoDB to ensure data integrity and improve the quality of your applications.

Understanding MongoDB Validation

MongoDB allows you to enforce data validation rules at the collection level. Validation rules can specify the structure of documents, require the presence of specific fields, restrict field types, enforce data ranges, and more. These rules help maintain data integrity by ensuring that only valid documents are inserted or updated in the collection.

Creating a Collection with Validation Rules

To create a collection with validation rules, you can use the db.createCollection() method. Here’s how:

db.createCollection("yourCollectionName", {
    validator: {
        $jsonSchema: {
            bsonType: "object",
            required: ["name", "email", "age"],
            properties: {
                name: {
                    bsonType: "string",
                    description: "must be a string and is required"
                },
                email: {
                    bsonType: "string",
                    pattern: "^.+@.+\\..+$",
                    description: "must be a valid email address and is required"
                },
                age: {
                    bsonType: "int",
                    minimum: 18,
                    maximum: 65,
                    description: "must be an integer in [18, 65] and is required"
                }
            }
        }
    },
    validationLevel: "strict",
    validationAction: "error"
});

This code snippet creates a new collection named yourCollectionName with validation rules that require documents to have a `name`, `email`, and `age` fields with specific types and constraints.

Modifying Validation Rules

To modify existing validation rules for a collection, use the db.runCommand() method with the collMod command:

db.runCommand({
  collMod: "yourCollectionName",
  validator: {
    $jsonSchema: {
      ... // your updated validation schema here
    }
  }
});

This allows you to update the validation schema for the collection without needing to redefine the entire collection.

Document Validation on Insert and Update Operations

Once validation rules are set, MongoDB enforces these rules on insert and update operations. If a document does not meet the validation criteria, the operation will fail with an error. Consider this example:

db.yourCollectionName.insert({
  name: "John Doe",
  email: "[email protected]"
});

This operation will fail because the `age` field is missing, violating the collection’s validation rules.

Tips for Effective Validation

  • Use descriptive descriptions: Use the description property in your schema to provide clear, actionable error messages.
  • Test your rules: Regularly test your validation rules to ensure they behave as expected.
  • Consider application-level validation: While MongoDB’s validation provides a safety net, validating data at the application level can offer more flexibility and control.

Advanced Validation Techniques

For more complex validation scenarios, MongoDB supports several advanced techniques, including:

  • Using the $expr operator to create expressions that validate documents based on the values of other fields.
  • Applying external JavaScript functions for custom validation logic.
  • Implementing compound validation rules that combine multiple conditions.

Conclusion

Implementing validation rules in MongoDB is a powerful way to ensure data integrity and consistency across your applications. By leveraging MongoDB’s schema validation features, you can enforce necessary data structures, types, and constraints, reducing bugs and improving user experience. Remember, while MongoDB validation is robust, combining it with application-level validation can provide the highest level of data integrity.

Through the clear, actionable examples provided in this tutorial, you now have a solid foundation to start implementing MongoDB data validation in your projects. Happy coding!

Next Article: What is BSON in MongoDB? Explained with examples

Previous Article: Working with Binary data in MongoDB (with examples)

Series: MongoDB Tutorials

MongoDB

You May Also Like

  • MongoDB: How to combine data from 2 collections into one
  • Hashed Indexes in MongoDB: A Practical Guide
  • Partitioning and Sharding in MongoDB: A Practical Guide (with Examples)
  • Geospatial Indexes in MongoDB: How to Speed Up Geospatial Queries
  • Understanding Partial Indexes in MongoDB
  • Exploring Sparse Indexes in MongoDB (with Examples)
  • Using Wildcard Indexes in MongoDB: An In-Depth Guide
  • Matching binary values in MongoDB: A practical guide (with examples)
  • Understanding $slice operator in MongoDB (with examples)
  • Caching in MongoDB: A practical guide (with examples)
  • CannotReuseObject Error: Attempted illegal reuse of a Mongo object in the same process space
  • How to perform cascade deletion in MongoDB (with examples)
  • MongoDB: Using $not and $nor operators to negate a query
  • MongoDB: Find SUM/MIN/MAX/AVG of each group in a collection
  • References (Manual Linking) in MongoDB: A Developer’s Guide (with Examples)
  • MongoDB: How to see all fields in a collection (with examples)
  • Type checking in MongoDB: A practical guide (with examples)
  • How to query an array of subdocuments in MongoDB (with examples)
  • MongoDB: How to compare 2 documents (with examples)