การรับประกัน ACID ในคลังเอกสารแบบกระจาย
ผู้เรียนจะเชื่อมโยงคุณสมบัติ ACID ทั้งสี่ประการกับกลไกจัดเก็บข้อมูลของ MongoDB และเข้าใจว่าคุณสมบัติใดมีให้โดยค่าเริ่มต้นในระดับเอกสารเดียว
การรับประกัน ACID ในคลังเอกสารแบบกระจาย เป็นบทเรียน MongoDB Academy ฟรีบน CoddyKit นี่คือบทเรียนที่ 1 จากทั้งหมด 4 บทเรียน คุณสามารถอ่านบทเรียนทั้งหมดด้านล่างฟรี — จากนั้นลองปฏิบัติด้วยตัวคุณเองในเบราว์เซอร์พร้อมตัวแก้ไขโค้ดในตัวและติวเตอร์ AI ตลอด 24/7 บทเรียนนี้เป็นส่วนหนึ่งของเส้นทางการเรียน MongoDB Academy และความก้าวหน้าของคุณจะซิงค์ข้ามเว็บและแอป CoddyKit คอร์ส MongoDB Academy มีบทเรียนทั้งหมด 4 บทเรียน
บางส่วนของบทเรียนนี้ยังไม่ได้รับการแปล และแสดงเป็นภาษาอังกฤษ
What ACID Means for Databases
ACID stands for Atomicity, Consistency, Isolation, and Durability—four properties that guarantee reliable processing of database operations. These properties were first defined for traditional relational databases but are equally important in document stores. Understanding how MongoDB provides (or trades off) each property helps you design data models and operations that meet your application's reliability requirements.
Atomicity: All or Nothing
Atomicity guarantees that a set of operations either all succeed or all fail—there is no partial state. In MongoDB, single-document operations are always atomic. When you call updateOne with multiple update operators, the entire change is applied as a single atomic unit. This is possible because all the data for one document is typically stored together on disk in BSON format.
// This entire updateOne is atomic — both fields change together or neither does
db.accounts.updateOne(
{ _id: accountId },
{
$inc: { balance: -100 },
$push: { transactions: { type: 'debit', amount: 100, date: new Date() } }
}
)Single-Document Atomicity vs Multi-Document
MongoDB guarantees atomicity at the single-document level by default. Because a document can contain embedded arrays and nested objects, you can often model what would be multiple SQL rows as one document and gain atomic updates for free. Multi-document atomicity requires explicit multi-document transactions (available since MongoDB 4.0 on replica sets). Understanding this distinction guides your data modeling decisions.
// No transaction needed: order + line items in one document = atomic
db.orders.insertOne({
_id: orderId,
customerId: customerId,
status: 'pending',
items: [
{ productId: 'P1', qty: 2, price: 29.99 },
{ productId: 'P2', qty: 1, price: 49.99 }
],
total: 109.97
})Consistency: Valid State Transitions
Consistency means the database always moves from one valid state to another. In MongoDB, consistency is enforced through JSON Schema validators (field types, required fields, enum values), unique indexes (no duplicate values), and application-level invariants. Unlike traditional RDBMS, MongoDB does not enforce foreign keys natively—your application code or schema design must maintain referential integrity.
// JSON Schema validator enforces consistency constraints
db.createCollection('users', {
validator: {
$jsonSchema: {
bsonType: 'object',
required: ['email', 'role'],
properties: {
email: { bsonType: 'string' },
role: { enum: ['admin', 'user', 'guest'] }
}
}
}
})Isolation: Concurrent Operation Behavior
Isolation controls how concurrent operations see each other's changes. MongoDB uses snapshot isolation for multi-document transactions: a transaction sees a consistent snapshot of the data as it was when the transaction started. Outside transactions, individual reads may see committed changes from other operations immediately—this is called read committed isolation. Read preferences on replica sets affect which snapshot you read from.
// Inside a transaction, a consistent snapshot is maintained
const session = client.startSession();
session.startTransaction();
try {
// These two reads see the SAME snapshot even if other writers commit between them
const inventory = await db.collection('inventory').findOne({ _id: itemId }, { session });
const order = await db.collection('orders').findOne({ _id: orderId }, { session });
// ...
await session.commitTransaction();
} finally {
await session.endSession();
}Durability: Surviving Failures
Durability guarantees that once an operation is acknowledged, it persists even if the system crashes. MongoDB achieves durability through the WiredTiger journal—writes are recorded in a journal before being applied to data files. The writeConcern option lets you control the level of durability: w:1 acknowledges after one node writes, w:majority waits until the majority of replica set members have persisted the write.
// w:majority ensures write survives even if the primary fails
db.payments.insertOne(
{ orderId: orderId, amount: 99.99, status: 'completed' },
{ writeConcern: { w: 'majority', j: true } }
// j:true = wait for journal flush on disk
)Single-Document Writes Are Always Durable
For single-document operations on a replica set with the default write concern, MongoDB waits for the primary to acknowledge the write before responding. If the operation has j:true, it also waits for the journal to flush to disk. This means single-document writes are durable against both primary crashes (replica set failover) and disk failures (journal ensures no data loss on restart).
// Default write concern on Atlas: {w: 'majority'} — already durable
// Explicitly requesting journal flush:
await db.collection('criticalAuditLog').insertOne(
{ event: 'payment', userId: userId, timestamp: new Date(), amount: 500 },
{ writeConcern: { w: 'majority', j: true } }
);The Embedded Document Advantage for ACID
One of MongoDB's key design insights is that embedding related data in a single document eliminates the need for multi-document transactions in many cases. An order with its line items, a blog post with its comments, a user profile with its addresses—all are single documents and therefore get atomic, consistent, isolated, and durable updates for free, without the overhead of a transaction.
// Updating shipping address + logging the change:
// One atomic write — no transaction needed
await db.collection('users').updateOne(
{ _id: userId },
{
$set: { 'address.street': '123 Main St', 'address.city': 'Austin' },
$push: {
addressHistory: {
changedAt: new Date(),
previous: oldAddress
}
}
}
)When You Do Need Multi-Document ACID
There are scenarios where embedding does not work and multi-document ACID is necessary. Financial transfers between two separate account documents (debit one, credit another) require atomicity across two documents. Inventory reservation (decrement stock in one collection, create order in another) needs isolation. Distributed ledger updates across many records require all-or-nothing guarantees. For these patterns, MongoDB 4.0+ multi-document transactions are the answer.
// Without a transaction, a crash between these two writes
// leaves the database in an inconsistent state (money debited but not credited):
await db.collection('accounts').updateOne({ _id: fromId }, { $inc: { balance: -100 } });
// <--- system crash here means money is lost!
await db.collection('accounts').updateOne({ _id: toId }, { $inc: { balance: 100 } });
// With a transaction, both succeed or both roll back.ACID vs BASE: A Spectrum
Not all NoSQL databases provide ACID guarantees. Many early NoSQL systems chose BASE (Basically Available, Soft state, Eventually consistent) to achieve higher write throughput and availability across distributed nodes. MongoDB positions itself as providing ACID at the document level by default and full ACID for multi-document transactions on request—a middle ground between strict RDBMS and purely eventual-consistent stores.
Read Your Own Writes: Causal Consistency
In distributed replica sets, a write on the primary and a subsequent read from a secondary might not see the write yet—this is a consistency anomaly. MongoDB's causal consistency feature (available via sessions) guarantees that operations within a session see the effects of all previous operations in that same session, even across different servers. This is critical for correct application behavior after writes.
// Causal consistency: guaranteed to read your own writes within a session
const session = client.startSession({ causalConsistency: true });
await db.collection('settings').updateOne(
{ _id: userId }, { $set: { theme: 'dark' } }, { session }
);
// This read is guaranteed to see the update above, even on a secondary:
const settings = await db.collection('settings').findOne({ _id: userId }, { session });
await session.endSession();Quick Check
Test your understanding of MongoDB & NoSQL Databases concepts from this lesson.
Lesson Recap
In this lesson you learned: all single-document operations in MongoDB are fully ACID-compliant by default, atomicity at the document level eliminates the need for transactions in many cases, and multi-document ACID transactions (MongoDB 4.0+) handle cases where embedding is not practical such as financial transfers between separate documents. Next up we explore how to open sessions and write multi-document transactions.
คำถามที่พบบ่อย
บทเรียน “การรับประกัน ACID ในคลังเอกสารแบบกระจาย” ฟรีหรือไม่
ใช่ — ข้อความเต็มของ “การรับประกัน ACID ในคลังเอกสารแบบกระจาย” ฟรีให้อ่านที่นี่บนเว็บ เพื่อปฏิบัติแบบโต้ตอบ (ตัวแก้ไขโค้ดในตัวและติวเตอร์ AI ตลอด 24/7) และปลดล็อคส่วนที่เหลือของคอร์ส MongoDB Academy ให้อัปเกรดเป็น CoddyKit PRO คอร์ส MongoDB Academy มีบทเรียนทั้งหมด 4 บทเรียน
คุณจะเรียนรู้อะไรในบทเรียน “การรับประกัน ACID ในคลังเอกสารแบบกระจาย”
ผู้เรียนจะเชื่อมโยงคุณสมบัติ ACID ทั้งสี่ประการกับกลไกจัดเก็บข้อมูลของ MongoDB และเข้าใจว่าคุณสมบัติใดมีให้โดยค่าเริ่มต้นในระดับเอกสารเดียว คุณปฏิบัติ MongoDB Academy ด้วยโค้ดที่ใช้งานได้จริงที่คุณเรียกใช้โดยตรงในเบราว์เซอร์ และติวเตอร์ AI ตลอด 24/7 ตอบคำถามของคุณขณะที่คุณไปผ่านบทเรียน
คุณต้องมีประสบการณ์ก่อนที่จะเริ่มเรียน MongoDB Academy หรือไม่
ไม่จำเป็นต้องมีประสบการณ์มาก่อน MongoDB Academy บน CoddyKit ออกแบบมาสำหรับผู้เริ่มต้นไปจนถึงผู้เรียนขั้นสูง คุณสามารถเริ่มต้นที่นี่หรือเริ่มจากตัวแรกและเรียนด้วยความเร็วของคุณเอง นี่คือบทเรียนที่ 1 จากทั้งหมด 4 บทเรียน
บทเรียน “การรับประกัน ACID ในคลังเอกสารแบบกระจาย” ใช้เวลานานแค่ไหน
บทเรียน CoddyKit ส่วนใหญ่ใช้เวลาประมาณ 5–10 นาที แต่ละบทเรียนจึงสั้นและเป็นแบบโต้ตอบ คุณสามารถก้าวหน้าอย่างต่อเนื่องและกลับมาเรียนต่อจากตรงที่เพิ่งหยุดบนเว็บและแอปได้เลย
ฉันเขียนและรันโค้ดในบทเรียน MongoDB Academy นี้ได้ไหม
ได้ บทเรียน MongoDB Academy ทุกบทมีตัวแก้ไขโค้ดในตัว คุณจึงเขียนและรันโค้ดจริงได้เลยในเบราว์เซอร์ และได้รับข้อเสนอแนะจาก AI ในทันที — ไม่ต้องติดตั้งในเครื่องของคุณ
บทเรียนทั้งหมดในหลักสูตรนี้
- การรับประกัน ACID ในคลังเอกสารแบบกระจาย
- การเริ่มเซสชันและธุรกรรมหลายเอกสาร
- การจัดการข้อผิดพลาดและตรรกะการลองใหม่
- ข้อพิจารณาด้านประสิทธิภาพของธุรกรรม