MongoDB Replication

Beginner
⏱️ 14 min read
📚 Updated: Jul 2026
🎯 5 Examples
High Availability

What You’ll Learn

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.

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.

🏗️ Replica set members

Member typeRoleAccepts writes?
PrimaryDefault target for reads/writes; records all changes to the oplogYes
SecondaryReplicates oplog; can serve reads with read preferenceNo (becomes primary after election)
ArbiterVotes in elections only; no data copy (avoid in new designs if possible)No
Hidden / delayedSpecial secondaries for backups or point-in-time recoveryNo

A typical production replica set has three data-bearing members across availability zones. That gives quorum for elections without relying on an arbiter.

📝 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 preferencesecondaryPreferred offloads reads when a secondary is available.
mongosh
// Node.js driver example
mongodb://mongo1:27017,mongo2:27017,mongo3:27017/mydb?replicaSet=rs0

// Write with majority concern
db.orders.insertOne(
  { item: "keyboard", qty: 2 },
  { writeConcern: { w: "majority", wtimeout: 5000 } }
);

⚡ Quick Reference

TaskCommand
Initiate replica setrs.initiate({ _id: "rs0", members: [...] })
Cluster healthrs.status()
Who is primary?db.hello().primary or rs.isMaster()
Add memberrs.add("host:27017")
Remove memberrs.remove("host:27017")
Step down primary (maintenance)rs.stepDown()
Replication lagrs.printSecondaryReplicationInfo()
Write concern
{ w: "majority" }

Durability across most nodes

Read preference
secondaryPreferred

Reads from secondary when OK

Minimum prod size
3 data-bearing members

Reliable elections

Dev single node
rs.initiate()  // 1 member

Enables transactions locally

🧰 Key concepts

Terms you will see in docs, monitoring, and rs.status() output:

oplog Core

Capped collection on the primary recording every write. Secondaries tail the oplog to stay synchronized.

local.oplog.rs
db.getReplicationInfo()
election Core

Raft-like vote when the primary disappears. Requires a majority of voting members. Typically completes in seconds.

rs.status().members
  .find(m => m.stateStr === "PRIMARY")
write concern Durability

How many members must confirm a write before the driver returns success. majority survives a single node loss.

{ w: 1 }           // primary only
{ w: "majority" }  // recommended prod
read preference Read scaling

Where drivers send read queries. primary (default) is strongly consistent; secondary may return slightly stale data.

primary
secondaryPreferred
nearest

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

How It Works

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 */

How It Works

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
*/

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);

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.

🧠 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.

📝 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.
  • Previous topic: Accumulators. Next: Sharding.

Conclusion

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.

💡 Best Practices

✅ Do

  • 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

Key Takeaways

Knowledge Unlocked

Five things to remember about replication

Use these points when designing a resilient MongoDB deployment.

5
Core concepts
📝 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.

Continue the MongoDB Series

Master replica sets for high availability, then learn how sharding scales beyond one cluster.

Next: Sharding →

About the author

Mari Selvan M P
Mari Selvan M P 🔗

Developer, cloud engineer, and technical writer

  • Experience 12 years building web and cloud systems
  • Focus Full Stack Development, AWS, and Developer Education

I write practical tutorials so students and working developers can learn by doing—from databases and APIs to deployment on AWS.

5 people found this page helpful