0% completed
JSON Schema validation in MongoDB allows you to enforce a specific structure for documents in a collection. This ensures that documents conform to a predefined schema, helping to maintain data integrity and consistency.
JSON Schema validation is a powerful tool for applications where the structure of data is critical, such as financial systems, e-commerce platforms, and content management systems. By specifying validation rules, you can prevent invalid data from being inserted into the database.
JSON Schema validation in MongoDB is specified when creating a collection using the validator
option. The schema is defined using standard JSON Schema syntax.
Let's create a products
collection with a schema validation to ensure each product has a name
, price
, and an optional tags
array.
Example:
db.createCollection("products", { validator: { $jsonSchema: { bsonType: "object", required: ["name", "price"], properties: { name: { bsonType: "string", description: "must be a string and is required" }, price: { bsonType: "double", minimum: 0, description: "must be a double and is required" }, tags: { bsonType: ["array"], items: { bsonType: "string" }, description: "must be an array of strings" } } } } })
Valid Document:
db.products.insertOne({ name: "Laptop", price: 999.99, tags: ["electronics", "computers"] })
Invalid Document (missing required price
field):
db.products.insertOne({ name: "Laptop", tags: ["electronics", "computers"] }) // This will throw an error due to schema validation.
You can modify the validation rules of an existing collection using the collMod
command.
Example:
db.runCommand({ collMod: "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 double 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" } } } } })
JSON Schema validation in MongoDB is a powerful feature that helps ensure data integrity and consistency. By defining a schema for your collections, you can prevent invalid data from being stored, making your application more robust and reliable.
.....
.....
.....