MongoDB Replication

Beginner
12 min read
Updated: Oct 2026
Concept guide
Live examples

What Is MongoDB Replication?

Replication keeps multiple copies of the same data on different mongod instances. If one server fails, another copy can keep the application running.

Main benefits: redundancy, high availability, automatic failover, better data availability, disaster-recovery copies, and—when configured—optional read distribution.

Remember
Replication = multiple live copies of the same data

Replica set → primary (writes) + secondaries (replicate)
Oplog       → log of operations secondaries apply
Failover    → election can choose a new primary

Not the same as a backup.

What Is a Replica Set?

A replica set is a group of mongod instances that maintain the same data set. At any time, one member is the primary; the others are secondaries.

The primary receives writes. Secondaries replicate changes from the primary so their data sets converge toward the same state.

Replica set
                Application
                     |
                     v
                  Primary
                 /        \
                v          v
           Secondary   Secondary

Why Use Replication?

ReasonWhat it gives you
Server failure protectionOther members still hold the data
High availabilityA new primary can be elected after failure
Multiple copiesRedundancy across machines or sites
Disaster recovery / reportingDedicated copies for special purposes
Geographic distributionData closer to users in more than one region
Optional read distributionSome reads can target secondaries (may be stale)

Replication is not a backup. Replication maintains additional current copies. Backups provide historical recovery points. You need both for a complete strategy.

How MongoDB Replication Works

Writes go to the primary. The primary records each change in its oplog. Secondaries read that oplog and apply the same operations asynchronously.

Replication flow
Application
     |
     v
  Primary
     |
     v
   Oplog
     |
     +----------+
     |          |
     v          v
Secondary   Secondary
  1. The application sends a write to the primary.
  2. The primary applies the write to its data.
  3. The primary records the operation in its oplog.
  4. Secondaries read operations from the oplog.
  5. Secondaries apply those operations to their own data.
  6. Members converge toward the same data set (async—not instant).

Primary and Secondary Members

Primary

The primary receives write operations, records changes in the oplog, and can serve reads. It may step down when needed. If it becomes unavailable, an election can select a new primary.

Secondary

A secondary replicates from the primary and keeps its own copy of the data. It can serve reads when the client’s read preference allows it, and an eligible secondary can become primary through an election.

Because replication is asynchronous, a secondary may briefly lag behind the primary. Secondary reads can therefore return data that is not yet identical to the primary.

Oplog

The oplog (operation log) is a special log of write operations on the primary. Secondaries use it as the source of truth for which changes to apply next.

Oplog idea
Primary changes:
price: 100 → 120

        ↓

Oplog records operation

        ↓

Secondary reads oplog

        ↓

Secondary applies change

How It Works

  1. A write changes data on the primary.
  2. That operation is recorded in the oplog.
  3. Each secondary reads new oplog entries.
  4. The secondary applies them so its data catches up.

Pseudocode

Pseudocode
Write data to Primary

Primary records the operation

Primary writes operation to oplog

Secondary reads oplog

Secondary applies operation

Repeat for future operations

Worked Walkthrough

Insert one product through the primary, then follow how secondaries catch up.

mongosh
db.products.insertOne({
  name: "Laptop",
  price: 75000
})
Path
Application
    ↓
Primary
    ↓
Oplog
    ↓
Secondary

How It Works

  1. The application sends the insert to the primary.
  2. The primary stores the document in products.
  3. The operation is recorded in the oplog.
  4. Secondaries replicate the operation from the oplog.
  5. Secondaries eventually contain the same document—not necessarily instantly.

Automatic Failover and Elections

If the primary becomes unavailable long enough, eligible members hold an election to choose a new primary.

Failover
Before failure:

Primary
   |
   +-- Secondary
   +-- Secondary


Primary fails

      X

Secondary A
     |
Election
     |
New Primary
  1. The set detects that the primary is unavailable.
  2. Eligible members participate in an election.
  3. A new primary is selected.
  4. Compatible drivers can detect the change and retry certain writes automatically.

By default, electionTimeoutMillis is 10 seconds (MongoDB’s documented default). Network conditions and configuration affect how long an election actually takes—do not treat failover as instant.

Replication Lag

Replication lag is the delay between an operation on the primary and the application of that operation on a secondary from the oplog.

Lag idea
Primary:
Insert Order #101
     |
     |  replication delay
     v
Secondary:
Insert Order #101
  • Small lag can be normal.
  • Large lag can signal performance or infrastructure problems.
  • Secondary reads can return older data while lag exists.
  • Monitor lag in production (for example with rs.status()).

Read Preference

Read preference controls which replica set member(s) a client uses for reads. The default is primary. Non-primary modes may return stale data because replication is asynchronous.

Read PreferenceBasic idea
primaryRead from the primary (default)
primaryPreferredPrefer the primary; use a secondary if needed
secondaryRead from secondary members only
secondaryPreferredPrefer a secondary; fall back to primary if needed
nearestRead from a suitable low-latency member (primary or secondary)

Write Concern

Write concern controls the level of acknowledgment requested for a write operation. For most deployments, the default is w: "majority".

mongosh
db.orders.insertOne(
  { orderId: 101, total: 500 },
  { writeConcern: { w: "majority" } }
)

How It Works

  1. The application performs the write.
  2. MongoDB waits for the requested acknowledgment level.
  3. With w: "majority", acknowledgment comes after a calculated majority of data-bearing voting members have durably recorded the change in their local oplog.

Read Concern vs Write Concern

ConceptControls
Read concernConsistency / isolation level for reads
Write concernHow a write is acknowledged
Read preferenceWhich member receives the read

Do not mix these up: preference chooses where to read; concern settings describe acknowledgment and consistency behavior.

Transactions and Replication

Multi-document transactions are available on replica sets. Transactions that contain reads must use read preference primary, and all operations in a transaction route to the same member.

Replication and transactions are different features: replication copies data across members; transactions group multiple operations into one atomic unit.

MongoDB Replication Examples

Short mongosh-oriented examples. Run them against a replica set (standalone servers do not demonstrate failover or secondary reads).

Example 1 — Insert Through the Primary

mongosh
db.products.insertOne({
  name: "Laptop",
  price: 75000
})

How It Works

  1. The write is sent to the current primary.
  2. The primary stores the document and records the op in the oplog.
  3. Secondaries apply the same insert asynchronously.

Example 2 — Configure Read Preference

Prefer secondaries for this session’s reads. Remember: data may be slightly behind the primary.

mongosh
db.getMongo().setReadPref("secondaryPreferred")

db.products.find({ name: "Laptop" })

How It Works

  1. setReadPref tells the client which members to prefer for reads.
  2. secondaryPreferred tries a secondary first, then the primary if needed.
  3. Returned documents might not yet include the absolute latest primary writes.

Example 3 — Majority Write Concern

mongosh
db.orders.insertOne(
  { orderId: 101, total: 500 },
  { writeConcern: { w: "majority" } }
)

How It Works

  1. The insert runs on the primary.
  2. The client waits for w: "majority" acknowledgment.
  3. A calculated majority of data-bearing voting members must durably record the change in their local oplog before the write is acknowledged.

Example 4 — Check Replica Set Status

Administrative command to inspect members, roles, and health.

mongosh
rs.status()

How It Works

  1. rs.status() reports replica set configuration and member state.
  2. Look for which member is PRIMARY vs SECONDARY.
  3. Use it when debugging lag, elections, or connectivity—not as an application API.

Edge Cases & Pitfalls

Common beginner mistakes around MongoDB replication.

async

Replication is asynchronous

Secondaries apply oplog entries later—not in lock-step with every primary write.

stale

Secondaries may lag

Do not assume a secondary always has the newest document. Prefer primary reads when freshness is required.

backup

Replication ≠ backup

Live copies do not replace point-in-time backups for accidental deletes or corruption.

reads

Read preference is not automatic

Default reads go to the primary. Secondary reads require an explicit non-primary read preference.

terms

Do not confuse the three “concern/preference” terms

Read preference = which member. Write concern = write acknowledgment. Read concern = read consistency/isolation.

election

Elections are not instant

Default detection uses a 10s election timeout; network conditions can extend the window without a writable primary.

scale

Replica sets are not unlimited read scaling

Secondary reads can help some workloads, but consistency, lag, and write amplification still matter. Scaling reads is a design choice, not free capacity.

Performance Notes

IdeaPractical tip
Extra workReplication adds network and storage work as ops propagate
Oplog applySecondaries must read and apply oplog entries continuously
LagMonitor lag; heavy write bursts can increase it
Secondary readsCan offload some reads—choose based on consistency needs, not speed alone
Write concernStronger acknowledgment can increase write latency

Cheat Sheet

ConceptRemember
Replica setGroup of MongoDB instances maintaining the same data
PrimaryReceives writes
SecondaryReplicates data from the primary
OplogRecords operations for replication
ElectionSelects a new primary when needed
Replication lagDelay between primary and secondary application
Read preferenceControls where reads are directed
Write concernControls write acknowledgment
Read concernControls read consistency / isolation behavior

Key Takeaways

  • Replication maintains multiple live copies of MongoDB data.
  • A replica set has one primary and one or more secondaries.
  • Writes go to the primary; secondaries apply oplog operations asynchronously.
  • Elections can select a new primary after failure; timing is not guaranteed.
  • Read preference routes reads; write concern controls acknowledgment.
  • Replication improves availability but does not replace backups.

One line: A replica set keeps the same data on multiple servers—writes hit the primary, secondaries follow the oplog, and elections restore a writable primary after failure.

Frequently Asked Questions

Replication keeps multiple copies of the same data across mongod instances in a replica set. It provides redundancy and high availability so the deployment can continue if a member fails.
A replica set is a group of mongod processes that maintain the same data set. One member is the primary (accepts writes); the others are secondaries that replicate the primary's oplog.
The primary receives write operations and records them in the oplog. Secondaries asynchronously apply those oplog operations to their own data. Clients read from the primary by default; read preference can target secondaries.
The oplog (operation log) is a special capped collection on the primary that records write operations. Secondaries read those entries and apply them so their data sets converge toward the primary.
No. Secondaries replicate the primary's oplog asynchronously. That means a secondary can temporarily lag behind the primary, and secondary reads may return stale data.
If the primary does not communicate with other members for longer than electionTimeoutMillis (10 seconds by default), an eligible secondary calls an election. A new primary is chosen; actual timing depends on configuration and network conditions.
Yes, by configuring read preference (for example secondary or secondaryPreferred). Non-primary modes may return stale data because replication is asynchronous.
Replication lag is the delay between an operation occurring on the primary and that same operation being applied on a secondary from the oplog. Small lag can be normal; large lag needs investigation.
Read preference controls which replica set member(s) a client uses for reads. The default is primary. Other modes can use secondaries but may see older data.
Write concern is the level of acknowledgment requested for a write. For example, w: "majority" asks MongoDB to acknowledge after a calculated majority of data-bearing voting members have durably recorded the change in their local oplog. It is the default for most deployments.
No. Replication keeps additional live copies of current data for availability. Backups provide historical recovery points. You still need a backup strategy.
There is no single universal number. Production topologies commonly use an odd count of voting members (often three) so the set can elect a primary with a majority. Exact size depends on availability goals, cost, geography, and whether you use arbiters—see the official MongoDB replica set documentation for deployment guidance.

Next: Sharding

Scale data across shards—each shard is typically a replica set.

Sharding tutorial →

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.

11 people found this page helpful