ข้อกังวลด้านการเขียนและความคงทนที่มีการยืนยัน
ผู้เรียนจะกำหนดค่าตัวเลือก w:majority, w:1 และการทำเจอร์นัล เพื่อปรับระดับการรับประกันความคงทนของการดำเนินการเขียน
ข้อกังวลด้านการเขียนและความคงทนที่มีการยืนยัน เป็นบทเรียน MongoDB Academy ฟรีบน CoddyKit นี่คือบทเรียนที่ 3 จากทั้งหมด 4 บทเรียน คุณสามารถอ่านบทเรียนทั้งหมดด้านล่างฟรี — จากนั้นลองปฏิบัติด้วยตัวคุณเองในเบราว์เซอร์พร้อมตัวแก้ไขโค้ดในตัวและติวเตอร์ AI ตลอด 24/7 บทเรียนนี้เป็นส่วนหนึ่งของเส้นทางการเรียน MongoDB Academy และความก้าวหน้าของคุณจะซิงค์ข้ามเว็บและแอป CoddyKit คอร์ส MongoDB Academy มีบทเรียนทั้งหมด 4 บทเรียน
บางส่วนของบทเรียนนี้ยังไม่ได้รับการแปล และแสดงเป็นภาษาอังกฤษ
What Is a Write Concern?
A write concern tells MongoDB how many replica set members must acknowledge a write before the driver considers it successful. It is the primary knob for trading durability (more acknowledgements = safer) against latency (fewer acknowledgements = faster). Every write operation — insert, update, delete, or replace — can specify its own write concern.
The w Option: Counting Acknowledgements
The w field controls how many members must confirm the write. w: 0 means fire-and-forget (no acknowledgement at all). w: 1 (default) means only the primary must confirm. w: 2 means the primary plus one secondary. w: 'majority' is the recommended production setting — it waits for a majority of voting members to confirm.
// w:1 — only primary acknowledges (default)
db.orders.insertOne({ item: 'pen' }, { writeConcern: { w: 1 } })
// w:majority — safe for production
db.orders.insertOne({ item: 'pen' }, { writeConcern: { w: 'majority' } })w: majority — The Recommended Setting
w: 'majority' guarantees that the write has been replicated to a majority of voting members before the driver receives a success response. This means a newly elected primary will always have seen the write — even after a failover. It is the only setting that prevents data rollback on primary failure.
// Set default write concern at the database level
db.runCommand({
setDefaultRWConcern: 1,
defaultWriteConcern: { w: 'majority', wtimeout: 5000 }
})The j Option: Journal Durability
The j (journal) option controls whether MongoDB waits for the write to be committed to the on-disk journal before acknowledging. With j: true, even a server crash immediately after acknowledgement cannot lose the write. Without journaling (j: false), a crash between the in-memory write and the next journal flush could lose the operation.
// Fully durable write: majority replication + journaled
db.payments.insertOne(
{ amount: 499.99, currency: 'USD' },
{ writeConcern: { w: 'majority', j: true, wtimeout: 5000 } }
)The wtimeout Option
wtimeout sets the maximum time (in milliseconds) the server waits for the required w acknowledgements. If the threshold is not met in time, MongoDB returns a WriteConcernError — but the write still happened on the primary. A timeout signals replication lag, not a write failure.
// Timeout after 3 seconds if secondaries are slow
db.logs.insertOne(
{ event: 'login', userId: 'u123' },
{ writeConcern: { w: 'majority', wtimeout: 3000 } }
)w:0 Fire-and-Forget: When to Use It
w: 0 sends the write and returns immediately without waiting for any acknowledgement. This maximises throughput for high-volume, loss-tolerant workloads like telemetry, analytics events, or log ingestion where occasional loss is acceptable. Never use it for financial transactions, user-generated content, or any data you cannot afford to lose.
// High-throughput metrics logging — loss acceptable
await db.collection('metrics').insertMany(
readings,
{ writeConcern: { w: 0 } }
)Write Concern and Rollback
When a primary fails and a secondary becomes primary, any writes the old primary had not yet replicated to a majority are rolled back. Those rolled-back writes are saved to a rollback folder on disk for manual recovery. Using w: 'majority' eliminates this risk because the write is only acknowledged after the majority has it.
Combining Write Concern With Transactions
In multi-document transactions, the write concern applies at the commit step, not on individual operations inside the transaction. Committing with w: 'majority' ensures all of the transaction's writes are durable on a majority before the application proceeds. Individual operation-level write concerns inside a transaction are ignored.
const session = client.startSession()
await session.withTransaction(async () => {
await orders.insertOne({ item: 'book' }, { session })
await inventory.updateOne({ _id: 1 }, { $inc: { qty: -1 } }, { session })
}, { writeConcern: { w: 'majority' } })Default Write Concern in MongoDB 5+
Since MongoDB 5.0, the implicit default write concern is w: 'majority' for replica sets and sharded clusters. Before 5.0, it defaulted to w: 1. This means that modern MongoDB deployments are safe by default, but you should still explicitly set write concerns in critical application code for clarity and portability.
// Verify the current default write concern
db.adminCommand({ getDefaultRWConcern: 1 })
// { defaultWriteConcern: { w: 'majority' }, ... }Write Concern at the Client Level
Write concern can be set at three levels: operation level (per insert/update), collection level (when getting a collection handle), or client/connection string level. More specific levels override broader ones. Setting it at the client level applies to all operations by default, while operation-level settings are best for cases that need special durability guarantees.
// Set write concern at MongoClient level
const client = new MongoClient(uri, {
writeConcern: { w: 'majority', j: true, wtimeout: 5000 }
})
// Override per-operation when needed
await db.criticalData.insertOne(doc, { writeConcern: { w: 3 } })Choosing the Right Write Concern
Pick your write concern based on data criticality. Financial/transactional data: w: 'majority', j: true. User content: w: 'majority'. Session/cache data: w: 1. High-volume telemetry: w: 0. The right choice balances the cost of losing data versus the latency penalty of waiting for additional acknowledgements.
Quick Check
Test your understanding of MongoDB & NoSQL Databases concepts from this lesson.
Lesson Recap
In this lesson you learned: write concern w controls how many members must acknowledge a write, w: 'majority' is the recommended production setting that prevents rollback after failover, and j: true adds on-disk journal durability for crash safety. Next up we explore read preferences and how to distribute read load across the replica set.
คำถามที่พบบ่อย
บทเรียน “ข้อกังวลด้านการเขียนและความคงทนที่มีการยืนยัน” ฟรีหรือไม่
ใช่ — ข้อความเต็มของ “ข้อกังวลด้านการเขียนและความคงทนที่มีการยืนยัน” ฟรีให้อ่านที่นี่บนเว็บ เพื่อปฏิบัติแบบโต้ตอบ (ตัวแก้ไขโค้ดในตัวและติวเตอร์ AI ตลอด 24/7) และปลดล็อคส่วนที่เหลือของคอร์ส MongoDB Academy ให้อัปเกรดเป็น CoddyKit PRO คอร์ส MongoDB Academy มีบทเรียนทั้งหมด 4 บทเรียน
คุณจะเรียนรู้อะไรในบทเรียน “ข้อกังวลด้านการเขียนและความคงทนที่มีการยืนยัน”
ผู้เรียนจะกำหนดค่าตัวเลือก w:majority, w:1 และการทำเจอร์นัล เพื่อปรับระดับการรับประกันความคงทนของการดำเนินการเขียน คุณปฏิบัติ MongoDB Academy ด้วยโค้ดที่ใช้งานได้จริงที่คุณเรียกใช้โดยตรงในเบราว์เซอร์ และติวเตอร์ AI ตลอด 24/7 ตอบคำถามของคุณขณะที่คุณไปผ่านบทเรียน
คุณต้องมีประสบการณ์ก่อนที่จะเริ่มเรียน MongoDB Academy หรือไม่
ไม่จำเป็นต้องมีประสบการณ์มาก่อน MongoDB Academy บน CoddyKit ออกแบบมาสำหรับผู้เริ่มต้นไปจนถึงผู้เรียนขั้นสูง คุณสามารถเริ่มต้นที่นี่หรือเริ่มจากตัวแรกและเรียนด้วยความเร็วของคุณเอง นี่คือบทเรียนที่ 3 จากทั้งหมด 4 บทเรียน
บทเรียน “ข้อกังวลด้านการเขียนและความคงทนที่มีการยืนยัน” ใช้เวลานานแค่ไหน
บทเรียน CoddyKit ส่วนใหญ่ใช้เวลาประมาณ 5–10 นาที แต่ละบทเรียนจึงสั้นและเป็นแบบโต้ตอบ คุณสามารถก้าวหน้าอย่างต่อเนื่องและกลับมาเรียนต่อจากตรงที่เพิ่งหยุดบนเว็บและแอปได้เลย
ฉันเขียนและรันโค้ดในบทเรียน MongoDB Academy นี้ได้ไหม
ได้ บทเรียน MongoDB Academy ทุกบทมีตัวแก้ไขโค้ดในตัว คุณจึงเขียนและรันโค้ดจริงได้เลยในเบราว์เซอร์ และได้รับข้อเสนอแนะจาก AI ในทันที — ไม่ต้องติดตั้งในเครื่องของคุณ
บทเรียนทั้งหมดในหลักสูตรนี้
- สมาชิกชุดแบบจำลอง: หลัก รอง และอาร์บิเตอร์
- การเลือกตั้งและการสลับทำงานแทนอัตโนมัติ
- ข้อกังวลด้านการเขียนและความคงทนที่มีการยืนยัน
- ค่ากำหนดการอ่าน: การกระจายภาระการอ่าน