When does MongoDB Check for Validation?
You should know that whenever you create a new collection with schema validation, MongoDB checks for validations only during updates and inserts in that collection. And when you specify validation rules for a pre-existing, non-empty collection, only the documents that are inserted after are checked for validations. The documents already present in the collection are not checked for validation until they are altered.
When you want to update the already existing schema we use ‘collMod’ command.
db.runCommand({
collMod: "Students",
validator: {
$jsonSchema: {
bsonType: "object",
required: ["name", "id", "age", "department", "marks"],
properties: {
name: {
bsonType: "string",
description: "Name must be a string.",
},
id: {
bsonType: "int",
description: "ID must be an integer.",
},
age: {
bsonType: "int",
minimum: 10,
description: "Age must be an integers greater than or equal to 10.",
},
department: {
bsonType: "string",
description: "Department must be a string.",
},
marks: {
bsonType: "int",
minimum: 0
description: "Marks must be integer greater than or equal to 0.",
},
},
},
},
});
Explanation: Here we included the marks field in the required property. We used ‘collMod’ to modify the schema defined earlier.
Note: ‘collMod’ will fail if the collection has the already existing documents that don’t follow the validation rules. So to modify the schema with ‘collMod’, ensure that the documents already present in the collection must be updated according to the schema or removed.
Schema Validation in MongoDB
MongoDB is a NoSQL and document-oriented database. MongoDB stores the records in a document in BSON format. Unlike SQL databases, it allows the documents in the collection to have different structures. There are some scenarios where the user needs to have a specific structure for the data stored in the document. This is a common practice to maintain data integrity and consistency.
Most relational databases store data in tabular format, which makes it difficult to store and handle big data. These days data is the key for any application to build. The more data the better the application’s performance. So to handle such big data we need a more reliable and user-friendly database.
A simple document structure in MongoDB will look like this:
{
title: 'w3wiki',
by: 'SaiRam Padala',
url: 'https://www.w3wiki.org',
type: 'NoSQL'
}