Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Selected Reading
How to validate documents before insert or update in MongoDB?
MongoDB provides built-in document validation to enforce data quality rules before inserting or updating documents. Use the validator option during collection creation to define validation criteria using MongoDB query operators.
Syntax
db.createCollection("collectionName", {
validator: {
$jsonSchema: { /* validation rules */ }
// OR
/* MongoDB query expression */
},
validationLevel: "strict", // or "moderate"
validationAction: "error" // or "warn"
});
Example 1: String Type Validation
Create a collection that only accepts documents where FirstName exists and is a string ?
db.createCollection("demo356", {
validator: {
$and: [
{"FirstName": {$type: "string", $exists: true}}
]
}
});
{ "ok" : 1 }
Valid Insert
db.demo356.insertOne({"FirstName": "Chris"});
{
"acknowledged" : true,
"insertedId" : ObjectId("5e568d49f8647eb59e5620c7")
}
Invalid Insert (Wrong Type)
db.demo356.insertOne({"FirstName": 909});
WriteError: Document failed validation
{
"index" : 0,
"code" : 121,
"errmsg" : "Document failed validation",
"op" : {
"_id" : ObjectId("5e568d52f8647eb59e5620c8"),
"FirstName" : 909
}
}
Example 2: JSON Schema Validation
db.createCollection("users", {
validator: {
$jsonSchema: {
bsonType: "object",
required: ["name", "email"],
properties: {
name: {
bsonType: "string",
description: "must be a string and is required"
},
email: {
bsonType: "string",
pattern: "^.+@.+$",
description: "must be a valid email format"
}
}
}
}
});
Verify Results
db.demo356.find();
{ "_id" : ObjectId("5e568d49f8647eb59e5620c7"), "FirstName" : "Chris" }
Key Points
- Validation occurs during insert and update operations
- Use
validationLevel: "moderate"to apply validation only to new/updated documents - Set
validationAction: "warn"to log violations instead of rejecting documents
Conclusion
MongoDB validation ensures data integrity by rejecting documents that don't meet defined criteria. Use $jsonSchema for complex validation or MongoDB query operators for simple type and existence checks.
Advertisements
