MongoDB Replication
Replication keeps multiple copies of your data in sync across servers, providing high availability and protecting against data loss. In MongoDB, this is implemented through replica sets.
1. What Is a Replica Set?
A replica set is a group of MongoDB instances maintaining the same data set. It consists of one Primary node (handles all writes) and multiple Secondary nodes (replicate data from the primary and can serve reads).
| Node Type | Role |
|---|---|
| Primary | Receives all write operations; replicates changes via the oplog |
| Secondary | Replicates data from primary; can serve read queries |
| Arbiter | Participates in elections but holds no data (tie-breaker) |
2. Setting Up a Replica Set
// Start three mongod instances with --replSet
mongod --replSet "rs0" --port 27017 --dbpath /data/db1
mongod --replSet "rs0" --port 27018 --dbpath /data/db2
mongod --replSet "rs0" --port 27019 --dbpath /data/db3
// Initiate the replica set from mongosh
rs.initiate({
_id: "rs0",
members: [
{ _id: 0, host: "localhost:27017" },
{ _id: 1, host: "localhost:27018" },
{ _id: 2, host: "localhost:27019" }
]
})
3. Automatic Failover
If the primary becomes unreachable, the remaining secondaries hold an election to promote a new primary — typically within seconds, minimizing downtime.
rs.status() // View current replica set state
rs.isMaster() // Check which node is currently primary
4. Read Preferences
| Read Preference | Behavior |
|---|---|
primary (default) | All reads go to the primary — strongest consistency |
primaryPreferred | Primary if available, else a secondary |
secondary | All reads from secondaries — reduces primary load |
nearest | Lowest network latency node, primary or secondary |
5. Write Concern
db.orders.insertOne(
{ item: "Book", qty: 3 },
{ writeConcern: { w: "majority", wtimeout: 5000 } }
)
w: "majority" ensures the write is acknowledged by a majority of replica set members before returning success — a strong durability guarantee.
6. Replication Checklist
- ✅ Understand primary/secondary/arbiter roles
- ✅ Initiate and verify a replica set
- ✅ Know how automatic failover elections work
- ✅ Configure read preferences appropriately
- ✅ Use write concern for durability guarantees
Ready to master MongoDB?
Build real-world MongoDB-powered applications with hands-on projects, mentor-led sessions, and placement support.