Minimal MRE

# Start replica set
mongod --replSet rs0 --port 27017 --dbpath /data/rs0-1 --bind_ip localhost --fork --logpath /data/rs0-1/mongod.log
mongod --replSet rs0 --port 27018 --dbpath /data/rs0-2 --bind_ip localhost --fork --logpath /data/rs0-2/mongod.log
mongod --replSet rs0 --port 27019 --dbpath /data/rs0-3 --bind_ip localhost --fork --logpath /data/rs0-3/mongod.log

# Initialize replica set
mongosh --port 27017
rs.initiate({ _id:"rs0", members:[
  {_id:0, host:"localhost:27017"},
  {_id:1, host:"localhost:27018"},
  {_id:2, host:"localhost:27019"}
]})

Problems with Master-Slave Replication

oplog is stored in the oplog.$main collection in the local database. oplog is idempotent; regardless of how many times it executes, the result is consistent.

oplog fields:

  • ts: Operation timestamp
  • h: Unique identifier for the operation
  • op: Operation type (i/u/d/c/n)
  • ns: Collection the operation targets
  • o: Operation content

Note: Master-slave replication is no longer supported after MongoDB 4.0.

Replica Set

What is a Replica Set

A replica set is a cluster of MongoDB instances that have the same data set. Replica sets provide data redundancy backup and store data copies on multiple servers.

Replica Set Advantages

  1. High availability: Automatic failover
  2. Data security and disaster recovery: Real-time data synchronization
  3. Read-write separation: Primary handles writes, secondaries handle read-only operations
  4. O&M advantages: Rolling upgrades, geographic distribution

Architecture Principles

oplog Log Structure

{
  "ts": Timestamp(1446011584, 2),
  "h": NumberLong("1687359108795812092"),
  "op": "i",
  "ns": "test.nosql",
  "o": { "_id": ObjectId(...), "name": "mongodb" }
}

Heartbeat Detection Mechanism

  • Heartbeat frequency: Default every 2 seconds
  • Timeout setting: Default 10 seconds
  • State maintenance: Each node maintains a state mapping table

Election Mechanism

Trigger election timing:

  • First initialization of replica set
  • Secondary node weight is higher than primary node
  • Secondary node discovers no primary in cluster
  • Primary node cannot access majority of members

Quick Reference

ParameterDefault ValueDescription
heartbeatIntervalMillis2000msHeartbeat frequency
heartbeatTimeoutSecs10sHeartbeat timeout threshold
electionTimeoutMillis10000msElection timeout
Max members50Replica set member limit
Max voting members7Member voting limit

Check commands:

  • db.getReplicationInfo(): View oplog status
  • rs.printSecondaryReplicationInfo(): View secondary replication status
  • rs.status(): View overall replica set status