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
- High availability: Automatic failover
- Data security and disaster recovery: Real-time data synchronization
- Read-write separation: Primary handles writes, secondaries handle read-only operations
- 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
| Parameter | Default Value | Description |
|---|---|---|
| heartbeatIntervalMillis | 2000ms | Heartbeat frequency |
| heartbeatTimeoutSecs | 10s | Heartbeat timeout threshold |
| electionTimeoutMillis | 10000ms | Election timeout |
| Max members | 50 | Replica set member limit |
| Max voting members | 7 | Member voting limit |
Check commands:
db.getReplicationInfo(): View oplog statusrs.printSecondaryReplicationInfo(): View secondary replication statusrs.status(): View overall replica set status