MongoDB Tutorial
- Home
- Introduction
- Installation
- Connection & Databases
- CRUD Operations
- Comparison Operators
- Logical Operators
- Array Operators
- Evaluation Operators
- Update Operators
- Projection & Sorting
- Cursor Methods
- Querying Nested Docs
- Upserts & Indexes
- Aggregation Framework
- Data Modeling
- Validations & Transactions
- Geospatial Queries
- Advanced Indexing
- MongoDB with Next.js
- Best Practices
Validations & Transactions
Modern applications require data integrity. MongoDB provides Schema Validation to enforce document structure and Transactions for ACID compliance.
1. Schema Validation
MongoDB allows you to define JSON Schema validation rules for your collections. Documents that don't match the rules will be rejected.
db.createCollection("students", {
validator: {
$jsonSchema: {
bsonType: "object",
required: ["name", "year", "major"],
properties: {
name: { bsonType: "string", description: "must be a string and is required" },
year: { bsonType: "int", minimum: 2017, maximum: 3017, description: "must be an integer in [ 2017, 3017 ] and is required" },
major: { enum: ["Math", "English", "Computer Science"], description: "can only be one of the enum values and is required" }
}
}
}
})2. Multi-Document Transactions
Transactions allow you to perform multiple operations (on one or more collections) as a single atomic unit. If any part fails, the entire transaction is rolled back.
Requirement: Transactions require a Replica Set or Sharded Cluster.
// Example Transaction using Node.js Driver
const session = client.startSession();
try {
await session.withTransaction(async () => {
// Operation 1: Deduct balance
await db.collection("accounts").updateOne(
{ name: "A" }, { $inc: { balance: -100 } }, { session }
);
// Operation 2: Add balance
await db.collection("accounts").updateOne(
{ name: "B" }, { $inc: { balance: 100 } }, { session }
);
});
} catch (error) {
console.log("Transaction aborted due to error:", error);
} finally {
await session.endSession();
}3. Validation Levels & Actions
- validationLevel: Defines how strictly MongoDB applies validation rules to existing documents (off, strict, moderate).
- validationAction: Determines whether MongoDB should
error(reject) orwarnbut allow the invalid document.
Pro Tip: Most developers use an ODM (Object Document Mapper) like Mongoose in Node.js to handle data validation at the application level.