Ensuring Data Integrity in MongoDB: Schema Validation
Learn how to enforce data consistency and integrity in MongoDB by implementing schema validation. Explore the use of JSON Schema to define rules and constraints for your documents, ensuring that your data adheres to a predefined structure. This guide will help you maintain data quality and prevent errors in your MongoDB applications.
MongoDB Schema Validation
MongoDB is schema-flexible by default, allowing documents in a collection to have different structures. However, schema validation rules can be defined to ensure a consistent structure across all documents in a collection.
Schema Validation with JSON Schema
MongoDB supports JSON Schema validation using the $jsonSchema
operator, which allows you to define the structure of documents in a collection.
Example: Creating a Collection with Schema Validation
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 command creates a collection named posts
with specified schema validation rules:
- title: Required field of type string.
- body: Required field of type string.
- category: Optional field of type string.
- likes: Optional field of type integer.
- tags: Optional field, must be an array of strings.
- date: Optional field of type date.
The schema validation ensures that all documents in the posts
collection adhere to these rules.