Replication keeps your MongoDB data safe and available by copying it across multiple servers in a replica set. If one server fails, another takes over as primary—your app keeps running.
01
Replica sets
Primary + secondaries.
02
Automatic failover
Elections pick a new primary.
03
Oplog
How changes replicate.
04
Read preference
Scale reads to secondaries.
05
Write concern
Confirm durability level.
06
rs.* commands
Init, status, add members.
Fundamentals
Definition and Usage
Replication is MongoDB’s built-in mechanism for high availability and data redundancy. Instead of relying on one mongod process, you deploy a replica set—a group of nodes that share the same data.
💡
Beginner tip
Connect your application to the replica set connection string, not a single host. The driver discovers the current primary and automatically fails over when elections occur.
The primary receives all writes. Secondaries replicate the primary’s oplog (operations log) and apply changes in order. An optional arbiter participates in elections but holds no data—useful only in specific legacy setups; data-bearing nodes are preferred.
Replication is the foundation for production MongoDB. Even sharded clusters store each shard as a replica set. Learn aggregation with pipeline stages first, then replication before scaling out horizontally.
Architecture
🏗️ Replica set members
Member type
Role
Accepts writes?
Primary
Default target for reads/writes; records all changes to the oplog
Yes
Secondary
Replicates oplog; can serve reads with read preference
No (becomes primary after election)
Arbiter
Votes in elections only; no data copy (avoid in new designs if possible)
No
Hidden / delayed
Special secondaries for backups or point-in-time recovery
No
A typical production replica set has three data-bearing members across availability zones. That gives quorum for elections without relying on an arbiter.
Foundation
📝 Syntax
Replica set administration uses rs.* helpers in mongosh on a connected mongod that has replication enabled:
mongosh
// Start mongod with --replSet rs0 (or replSetName in mongod.conf)
// Initiate the replica set (first member)
rs.initiate({
_id: "rs0",
members: [
{ _id: 0, host: "localhost:27017" }
]
});
// Check health and roles
rs.status();
// Add another member
rs.add("mongodb2.example.net:27017");
// View configuration
rs.conf();
Syntax Rules
replSetName — every member must share the same replica set name in config.
Odd member count — 3, 5, or 7 voting members avoids split-brain tie votes.
Initiate once — run rs.initiate() only on a fresh set; use rs.add() to grow.
Connection string — apps use mongodb://host1,host2,host3/?replicaSet=rs0.
Write concern — { w: "majority" } waits for most members to acknowledge writes.
Read preference — secondaryPreferred offloads reads when a secondary is available.
Where drivers send read queries. primary (default) is strongly consistent; secondary may return slightly stale data.
primary
secondaryPreferred
nearest
Hands-On
Examples Gallery
Set up a dev replica set, inspect roles, write with durability guarantees, and add a member—commands you run in mongosh after starting mongod with a replica set name.
📚 Getting Started
Start mongod with replication enabled, then initiate the set.
Example 1 — Initiate a single-node replica set (dev)
Start mongod with --replSet rs0, then run:
mongosh
rs.initiate({
_id: "rs0",
members: [{ _id: 0, host: "localhost:27017" }]
});
// Wait for PRIMARY state (prompt shows rs0 [primary])
db.runCommand({ hello: 1 });
/* Enables transactions, change streams, and
matches Atlas-style topology for local testing */
How It Works
Even one member forms a valid replica set. The node elects itself primary. This is the quickest way to unlock multi-document transactions on a laptop.
Example 2 — Inspect replica set health
mongosh
rs.status();
// Shorter summary
rs.status().members.forEach(function (m) {
print(m.name, "→", m.stateStr,
"lag:", m.optimeDate ? "synced" : "n/a");
});
db.hello().primary; // current primary host
db.hello().me; // this node's role
rs.status() is your first debug command when apps report connection errors—check which node is primary and whether any member is unreachable or stuck in recovery.
📈 Practical Patterns
Durability settings, read scaling, and growing the cluster.
Example 3 — Write with majority concern
mongosh
db.orders.insertOne(
{ orderId: "ORD-9001", total: 149.99, status: "paid" },
{ writeConcern: { w: "majority", j: true, wtimeout: 5000 } }
);
/* w: "majority" → acknowledged on most voting members
j: true → journaled to disk on those members
wtimeout → fail fast instead of hanging forever */
Majority write concern means the order survives loss of one node in a three-member set—the write is replicated before the app proceeds.
Example 4 — Read from a secondary
mongosh
// In mongosh (secondaryOk required for direct secondary reads)
db.getMongo().setReadPref("secondaryPreferred");
db.products.find({ category: "electronics" }).limit(5);
/* Driver connection string equivalent:
mongodb://host1,host2,host3/mydb
?replicaSet=rs0&readPreference=secondaryPreferred
*/
📤 Note:
secondaryPreferred → secondary if available,
otherwise falls back to primary
How It Works
Offloading analytics reads to secondaries protects primary CPU for writes. Accept that secondary reads may lag milliseconds to seconds behind the primary.
Example 5 — Add a member to the replica set
mongosh
// On the new host: start mongod with same --replSet rs0
// From mongosh connected to primary:
rs.add({ host: "mongo2.example.net:27017", priority: 1, votes: 1 });
rs.status(); // new member starts as STARTUP2, then SECONDARY
// Optional: adjust election priority (higher = preferred primary)
cfg = rs.conf();
cfg.members[1].priority = 0.5;
rs.reconfig(cfg);
📤 Initial sync:
New secondary copies all databases from primary
(state: STARTUP2) before becoming SECONDARY
How It Works
New members perform an initial sync—copy all data from the primary—then tail the oplog. Plan capacity before adding nodes; large datasets take time to clone.
Compare
📋 Replication vs related deployment options
Deployment
Data copies
Failover
Best for
Standalone mongod
One
Manual restore from backup
Local dev, prototypes
Replica set
Same data on each member
Automatic election
Production HA (most apps)
Sharded cluster
Data partitioned; each shard is a replica set
Per-shard failover
Very large scale-out workloads
Atlas M0/M10
Managed replica set
Atlas handles ops
Teams skipping self-hosting
Read: primary
Latest data
N/A
Financial, inventory counts
Read: secondaryPreferred
May be slightly stale
N/A
Dashboards, reporting
🧠 How Replication Works
1
Write hits primary
The application sends inserts, updates, and deletes to the current primary node.
Write
2
Oplog entry recorded
Each operation is appended to the capped oplog on the primary.
Oplog
3
Secondaries replicate
Secondary nodes pull oplog batches and apply them in the same order.
Sync
4
Primary fails → election
Remaining members vote; the most eligible secondary becomes the new primary.
Failover
=
🛡
High availability
Apps reconnect to the new primary and continue with redundant data copies intact.
Important
📝 Notes
Three members minimum for production—survives one failure with quorum for elections.
Even member counts (2, 4) need careful tie-breaking; odd counts are simpler.
Transactions and change streams require a replica set or sharded cluster—not standalone mongod.
Replication lag on a secondary means stale reads—monitor before routing critical queries there.
Backups: snapshot a secondary or use hidden/delayed members to avoid load on the primary.
Atlas clusters are replica sets by default—no manual rs.initiate() required.
Replication turns a single point of failure into a resilient cluster. A replica set keeps identical copies of your data, elects a new primary automatically, and lets you tune read preference and write concern for your durability needs.
Start with a local single-node replica set for development, then plan three production members before you go live. When data outgrows one replica set, learn sharding next—but never skip replication.
Deploy three data-bearing nodes across failure domains (racks / AZs)
Use replica set connection strings in every application environment
Set writeConcern: { w: "majority" } for critical financial data
Monitor replication lag and disk space on the oplog volume
Test failover drills—kill primary in staging and verify app recovery
Use rs.stepDown() before planned maintenance on the primary
❌ Don’t
Run production on a standalone mongod without backups and a recovery plan
Read from secondaries when you require absolutely up-to-the-millisecond data
Add arbiters instead of a third data node unless you understand the trade-offs
Ignore a member stuck in ROLLBACK or RECOVERING state
Assume two-node sets are safe—one failure loses quorum for writes
Reconfigure voting members during an active election window
Summary
Key Takeaways
Knowledge Unlocked
Five things to remember about replication
Use these points when designing a resilient MongoDB deployment.
5
Core concepts
🛡01
Replica set
Primary + secondaries.
Basics
📝02
Oplog
Ordered change log.
Sync
🔄03
Failover
Automatic elections.
HA
📖04
Read pref
Scale read traffic.
Reads
✅05
w: majority
Durable writes.
Writes
❓ Frequently Asked Questions
Replication keeps copies of your data on multiple MongoDB servers called a replica set. If the primary node fails, a secondary is elected as the new primary so applications can keep running with minimal downtime.
A replica set is a group of mongod processes that maintain the same data set. One member is primary (handles writes); others are secondaries (replicate the oplog). Most production deployments use at least three members for reliable elections.
The primary accepts all writes and records them in the oplog. Secondaries pull oplog entries and apply them to stay in sync. Clients read from the primary by default; read preference can target secondaries for scaling reads.
When the primary becomes unreachable, replica set members hold an election. The secondary with the most up-to-date oplog and sufficient votes becomes primary. MongoDB drivers retry writes against the new primary automatically when configured.
A standalone mongod is fine for learning and solo dev. Use a replica set when you need to test transactions, change streams, or failover behavior—or match production topology. Atlas free tier provides a three-node replica set out of the box.
Replication lag is how far behind a secondary is compared to the primary, measured in seconds or oplog entries. High lag means reads from that secondary may return stale data. Monitor lag with rs.status() and serverStatus.repl.
Did you know?
MongoDB drivers cache the replica set topology from the initial seed hosts and refresh it on each election. That is why you should list multiple members in your connection string—even if one host is down at startup, the driver can still discover the primary. See the official replication documentation.