How do Replica Sets provide high availability and automatic failover in MongoDB?
A MongoDB **Replica Set** is a cluster of `mongod` nodes that maintain the exact same dataset. It typically consists of one **Primary** node and multiple **Secondary** nodes.
• The Primary receives all write operations and records changes to its replication log (`oplog`). • Secondaries continuously tail and apply the primary's `oplog`. • If the Primary goes down or loses network heartbeat for more than 10 seconds, the remaining secondaries conduct an automated election to vote in a new Primary without application downtime.
// MongoDB Connection string with Replica Set discovery
mongodb://user:pass@node1.db.internal:27017,node2.db.internal:27017,node3.db.internal:27017/app_prod?replicaSet=rs0&readPreference=secondaryPreferred&w=majoritySpecifying `w=majority` ensures write operations only return success after a majority of replica nodes confirm persisting the change to disk, preventing data loss during failovers.
Ready for Sharding?
Take a quick test to evaluate yourself, or move straight to the next module.