0Pricing
MongoDB Academy · บทเรียน

ค่ากำหนดการอ่าน: การกระจายภาระการอ่าน

ผู้เรียนจะกำหนดค่ากำหนดการอ่าน primary, primaryPreferred, secondary, nearest และแบบติดแท็ก เพื่อกระจายการอ่านไปทั่วชุดแบบจำลอง

ค่ากำหนดการอ่าน: การกระจายภาระการอ่าน เป็นบทเรียน MongoDB Academy ฟรีบน CoddyKit นี่คือบทเรียนที่ 4 จากทั้งหมด 4 บทเรียน คุณสามารถอ่านบทเรียนทั้งหมดด้านล่างฟรี — จากนั้นลองปฏิบัติด้วยตัวคุณเองในเบราว์เซอร์พร้อมตัวแก้ไขโค้ดในตัวและติวเตอร์ AI ตลอด 24/7 บทเรียนนี้เป็นส่วนหนึ่งของเส้นทางการเรียน MongoDB Academy และความก้าวหน้าของคุณจะซิงค์ข้ามเว็บและแอป CoddyKit คอร์ส MongoDB Academy มีบทเรียนทั้งหมด 4 บทเรียน

บางส่วนของบทเรียนนี้ยังไม่ได้รับการแปล และแสดงเป็นภาษาอังกฤษ

What Is a Read Preference?

A read preference controls which replica set member the driver sends read operations to. By default, all reads go to the primary to ensure you always see the latest data. However, redirecting reads to secondaries can reduce load on the primary and bring reads geographically closer to users — at the cost of potentially reading slightly stale data.

primary: Always Read From Primary

primary (the default) routes every read to the primary. This guarantees strong consistency — you will always read your own writes and see the most up-to-date data. The downside is that the primary handles all read and write traffic. Use this mode whenever stale data would be unacceptable, such as in financial applications or user-facing dashboards.

// Explicit primary read preference (this is the default)
const col = db.collection('accounts', {
  readPreference: 'primary'
})
await col.findOne({ _id: userId })

primaryPreferred: Fallback to Secondary

primaryPreferred reads from the primary when it is available but falls back to a secondary if the primary is unreachable. This provides a balance: you normally get fresh data, but the application degrades gracefully during primary elections. Be aware that during the fallback, you may read data that is a few seconds behind.

const col = db.collection('products', {
  readPreference: 'primaryPreferred'
})
await col.find({}).toArray()

secondary: Read Only From Secondaries

secondary sends all reads to available secondaries, never touching the primary. This is ideal for analytics queries, batch jobs, or reporting that can tolerate eventual consistency. It offloads significant read pressure from the primary. If no secondary is available, the operation fails — it will NOT fall back to the primary.

// Route analytics query to secondary
const col = db.collection('events', {
  readPreference: 'secondary'
})
const count = await col.countDocuments({ type: 'click' })

secondaryPreferred: Secondary With Fallback

secondaryPreferred prefers secondaries but falls back to the primary if no secondary is available. This is the most commonly used non-default mode — it spreads read load across secondaries under normal conditions while remaining available when a secondary goes down. The caveat is the same as secondary: reads may be slightly stale.

const col = db.collection('catalog', {
  readPreference: 'secondaryPreferred'
})
await col.find({ category: 'books' }).toArray()

nearest: Lowest Network Latency

nearest sends reads to the member with the lowest measured network round-trip time, regardless of whether it is primary or secondary. This is perfect for globally distributed applications where users in different regions should read from the closest data center. Note that different users may read from different members, so they may temporarily see different data states.

const col = db.collection('content', {
  readPreference: 'nearest'
})
await col.findOne({ slug: 'hello-world' })

Tag Sets: Targeting Specific Members

Tag sets let you label replica set members (e.g., { region: 'us-east' }, { purpose: 'analytics' }) and then write read preferences that target only matching members. This enables sophisticated routing: send application reads to the nearest region and analytics queries to a dedicated secondary, all within the same replica set.

// Tag a member in replica set config
let cfg = rs.conf()
cfg.members[2].tags = { region: 'eu-west', purpose: 'analytics' }
rs.reconfig(cfg)

// Read from eu-west analytics member
const col = db.collection('reports', {
  readPreference: new ReadPreference('secondary', [{ region: 'eu-west' }])
})

Stale Reads and Replication Lag

When reading from secondaries, you may encounter stale reads — the secondary hasn't replicated the latest writes from the primary yet. The staleness depends on replication lag. MongoDB 3.6 introduced maxStalenessSeconds: the driver refuses to use a secondary lagging more than the specified number of seconds, preventing very stale reads.

// Reject secondaries more than 90 seconds behind
const col = db.collection('products', {
  readPreference: new ReadPreference(
    'secondaryPreferred',
    [],
    { maxStalenessSeconds: 90 }
  )
})

Read Preference in the Connection String

You can set the default read preference for all operations in the connection string using the readPreference parameter. This is the easiest way to configure the default without changing every call site. Individual operations can still override it by passing a readPreference option explicitly.

// Connection string with secondaryPreferred default
const uri = 'mongodb+srv://host/db?readPreference=secondaryPreferred&maxStalenessSeconds=120'
const client = new MongoClient(uri)

Read Preference and Transactions

Multi-document transactions must always use primary read preference. Operations inside a transaction that specify a different read preference will throw an error. This ensures that all reads within the same transaction see a consistent snapshot as of the transaction's start time on the primary.

// Inside a transaction, reads always go to primary
const session = client.startSession()
await session.withTransaction(async () => {
  // This implicitly uses primary read preference
  const order = await db.orders.findOne({ _id: orderId }, { session })
  await db.inventory.updateOne({ sku: order.sku }, { $inc: { qty: -1 } }, { session })
})

Choosing Read Preference in Practice

Use this guide: Real-time user data (cart, profile, notifications) → primary. Product catalog, content → secondaryPreferred. Reports and analytics → secondary with a dedicated analytics member. Global CDN-like reads → nearest. Always measure replication lag before routing critical reads to secondaries.

Quick Check

Test your understanding of MongoDB & NoSQL Databases concepts from this lesson.

Lesson Recap

In this lesson you learned: read preferences control which replica set member handles read operations, secondary and secondaryPreferred offload read traffic at the cost of eventual consistency, and nearest minimises latency in geo-distributed deployments. Next up we explore sharding — MongoDB's strategy for scaling beyond a single replica set.

คำถามที่พบบ่อย

บทเรียน “ค่ากำหนดการอ่าน: การกระจายภาระการอ่าน” ฟรีหรือไม่

ใช่ — ข้อความเต็มของ “ค่ากำหนดการอ่าน: การกระจายภาระการอ่าน” ฟรีให้อ่านที่นี่บนเว็บ เพื่อปฏิบัติแบบโต้ตอบ (ตัวแก้ไขโค้ดในตัวและติวเตอร์ AI ตลอด 24/7) และปลดล็อคส่วนที่เหลือของคอร์ส MongoDB Academy ให้อัปเกรดเป็น CoddyKit PRO คอร์ส MongoDB Academy มีบทเรียนทั้งหมด 4 บทเรียน

คุณจะเรียนรู้อะไรในบทเรียน “ค่ากำหนดการอ่าน: การกระจายภาระการอ่าน”

ผู้เรียนจะกำหนดค่ากำหนดการอ่าน primary, primaryPreferred, secondary, nearest และแบบติดแท็ก เพื่อกระจายการอ่านไปทั่วชุดแบบจำลอง คุณปฏิบัติ MongoDB Academy ด้วยโค้ดที่ใช้งานได้จริงที่คุณเรียกใช้โดยตรงในเบราว์เซอร์ และติวเตอร์ AI ตลอด 24/7 ตอบคำถามของคุณขณะที่คุณไปผ่านบทเรียน

คุณต้องมีประสบการณ์ก่อนที่จะเริ่มเรียน MongoDB Academy หรือไม่

ไม่จำเป็นต้องมีประสบการณ์มาก่อน MongoDB Academy บน CoddyKit ออกแบบมาสำหรับผู้เริ่มต้นไปจนถึงผู้เรียนขั้นสูง คุณสามารถเริ่มต้นที่นี่หรือเริ่มจากตัวแรกและเรียนด้วยความเร็วของคุณเอง นี่คือบทเรียนที่ 4 จากทั้งหมด 4 บทเรียน

บทเรียน “ค่ากำหนดการอ่าน: การกระจายภาระการอ่าน” ใช้เวลานานแค่ไหน

บทเรียน CoddyKit ส่วนใหญ่ใช้เวลาประมาณ 5–10 นาที แต่ละบทเรียนจึงสั้นและเป็นแบบโต้ตอบ คุณสามารถก้าวหน้าอย่างต่อเนื่องและกลับมาเรียนต่อจากตรงที่เพิ่งหยุดบนเว็บและแอปได้เลย

ฉันเขียนและรันโค้ดในบทเรียน MongoDB Academy นี้ได้ไหม

ได้ บทเรียน MongoDB Academy ทุกบทมีตัวแก้ไขโค้ดในตัว คุณจึงเขียนและรันโค้ดจริงได้เลยในเบราว์เซอร์ และได้รับข้อเสนอแนะจาก AI ในทันที — ไม่ต้องติดตั้งในเครื่องของคุณ

บทเรียนทั้งหมดในหลักสูตรนี้

  1. สมาชิกชุดแบบจำลอง: หลัก รอง และอาร์บิเตอร์
  2. การเลือกตั้งและการสลับทำงานแทนอัตโนมัติ
  3. ข้อกังวลด้านการเขียนและความคงทนที่มีการยืนยัน
  4. ค่ากำหนดการอ่าน: การกระจายภาระการอ่าน
← กลับไปที่ MongoDB Academy