0Pricing
MongoDB Academy · 课时

副本集成员:主节点、从节点和仲裁者

您将描述每个副本集成员的作用,并追踪写入如何通过操作日志从主节点流向从节点。

副本集成员:主节点、从节点和仲裁者 是 CoddyKit 上的免费 MongoDB Academy 课时。 这是第 1 节课,共 4 节。 你可以在下方免费阅读本课时的完整内容 — 然后在浏览器中使用内置代码编辑器和全天候 AI 导师进行实践。 这是 MongoDB Academy 学习路径的一部分,你的进度在网页和 CoddyKit 应用中同步。 MongoDB Academy 课程共包含 4 节课。

本课时的部分内容尚未翻译,以英文显示。

What Is a Replica Set?

A replica set is a group of MongoDB servers that all hold the same data, providing high availability and redundancy. If one server fails, another automatically takes over. A typical replica set has three or more members: at least one primary, one or more secondaries, and optionally an arbiter.

The Primary: Source of Truth

The primary is the only member that accepts write operations. All clients send inserts, updates, and deletes to the primary. It records every write operation in a special log called the oplog (operations log), which secondaries then read to stay in sync.

// Check which member is primary in mongosh
rs.isMaster()
// or
rs.status()

The Secondary: Hot Standby

A secondary replicates data from the primary by continuously tailing the primary's oplog and applying the same operations to its own copy of the data. Secondaries can serve read queries (with the right read preference) and will take over as primary if the current primary becomes unavailable.

// View oplog on a secondary
use local
db.oplog.rs.find().sort({$natural: -1}).limit(5)

Oplog: The Replication Backbone

The oplog (operations log) is a special capped collection stored in the local database on every replica set member. Every write to the primary is appended to the oplog. Secondaries read the oplog and replay each entry in order, keeping their data identical to the primary. The oplog's size determines how far behind a secondary can fall before needing a full resync.

// Check oplog size and time range
use local
db.oplog.rs.stats().maxSize
db.oplog.rs.find({},{ts:1,op:1,ns:1}).sort({$natural:-1}).limit(3)

The Arbiter: Tiebreaker Member

An arbiter is a lightweight replica set member that holds no data. Its sole purpose is to participate in elections by casting a vote when a new primary needs to be chosen. Arbiters are used in even-member sets (e.g., two data-bearing members) to ensure a majority can always be reached without the cost of a third full data node.

// Add an arbiter to the replica set
rs.addArb('hostname:27017')

Votes and Elections Overview

Each replica set member has a vote (0 or 1). A primary is elected by majority vote. With 3 members (each with 1 vote), a majority is 2. If the primary goes down, the remaining two members hold an election and the one with the most up-to-date oplog typically wins. Elections complete in seconds under normal network conditions.

// View all members and their vote configuration
rs.conf().members.forEach(m => {
  print(m.host, 'votes:', m.votes, 'priority:', m.priority)
})

Member Priorities

Each member has a priority value (default 1). A member with higher priority is preferred as primary in elections. Setting priority to 0 prevents a member from ever becoming primary — useful for secondaries in distant data centers that should serve local reads but not take writes from the primary region.

// Set a member to never become primary (priority 0)
let cfg = rs.conf()
cfg.members[2].priority = 0
rs.reconfig(cfg)

Hidden and Delayed Secondaries

Hidden secondaries (priority 0, hidden: true) are invisible to drivers and used only for backups or analytics without affecting the primary election pool. Delayed secondaries intentionally lag behind the primary by a configured number of seconds, providing a rolling recovery window in case of accidental data corruption.

// Configure a delayed secondary (e.g., 1 hour behind)
let cfg = rs.conf()
cfg.members[2].hidden = true
cfg.members[2].priority = 0
cfg.members[2].secondaryDelaySecs = 3600
rs.reconfig(cfg)

Checking Replication Lag

Replication lag is the delay between when a write is committed on the primary and when it appears on a secondary. High lag means secondaries serve stale data. You can monitor lag with rs.printSecondaryReplicationInfo() or by comparing the oplog timestamps between members. Atlas provides built-in lag alerts.

// Print replication lag for each secondary
rs.printSecondaryReplicationInfo()

// Example output:
// source: secondary1:27017
// syncedTo: Sat Jun 21 2025 10:00:00
// 0 secs (0 hrs) behind the primary

rs.status() Output Explained

rs.status() returns the full health snapshot of the replica set. Key fields to inspect: stateStr (PRIMARY / SECONDARY / ARBITER / DOWN), optimeDate (last applied oplog entry), health (1 = healthy, 0 = unreachable), and lastHeartbeatMessage for error details on troubled members.

rs.status().members.forEach(m => {
  print(m.name, m.stateStr, 'health:', m.health)
})

Data Writes Flow End to End

When a client writes a document, the flow is: 1) Driver sends write to the primary. 2) Primary applies the write to WiredTiger storage. 3) Primary appends the operation to its oplog. 4) Secondaries pull the oplog entry and apply it. 5) Primary acknowledges the client according to the configured writeConcern.

// Write with w:majority ensures secondaries have acknowledged
db.orders.insertOne(
  { item: 'laptop', qty: 1 },
  { writeConcern: { w: 'majority', wtimeout: 5000 } }
)

Quick Check

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

Lesson Recap

In this lesson you learned: the primary accepts all writes and records them in the oplog, secondaries replicate from the oplog to maintain identical copies, and arbiters hold no data but cast votes in elections. Next up we explore how MongoDB automatically elects a new primary when the current one fails.

常见问题解答

「副本集成员:主节点、从节点和仲裁者」课时是免费的吗?

是的 — 「副本集成员:主节点、从节点和仲裁者」的完整文本可在网页上免费阅读。要进行交互式练习(内置代码编辑器和全天候 AI 导师)并解锁 MongoDB Academy 课程的其余内容,请升级到 CoddyKit PRO。 MongoDB Academy 课程共包含 4 节课。

「副本集成员:主节点、从节点和仲裁者」这节课中我会学到什么?

您将描述每个副本集成员的作用,并追踪写入如何通过操作日志从主节点流向从节点。 你通过在浏览器中直接运行的动手代码来练习 MongoDB Academy,全天候 AI 导师会在你学习这节课的过程中回答你的问题。

学习 MongoDB Academy 需要有经验吗?

无需任何先前经验。CoddyKit 上的 MongoDB Academy 课程适合初学者到高级学习者,你可以从这里开始或从头开始,按照自己的节奏学习。 这是第 1 节课,共 4 节。

「副本集成员:主节点、从节点和仲裁者」课时需要多长时间?

大多数 CoddyKit 课程大约需要 5–10 分钟。每节课都很精短且互动,所以你能稳步进步,并在网页和应用中从离开的地方继续。

我能在这节 MongoDB Academy 课中编写并运行代码吗?

能。每节 MongoDB Academy 课都包含内置代码编辑器,你可以在浏览器中直接编写并运行真实代码,并获得即时 AI 反馈 — 无需本地设置。

此课程中的所有课时

  1. 副本集成员:主节点、从节点和仲裁者
  2. 选举和自动故障转移
  3. 写关注和已确认的持久性
  4. 读取偏好:分配读取负载
← 返回 MongoDB Academy