MongoDB replication maintains multiple copies of data across MongoDB servers. A group of MongoDB servers that maintain the same data set is called a replica set. Replication helps provide data availability and supports recovery when a server becomes unavailable.
Replication is the process of maintaining copies of database data on multiple servers.
For example, a school management system stores:
If the primary server becomes unavailable, an eligible secondary member may be elected as the new primary. This helps the application continue operating, subject to the replica set's health and configuration.
Replication is not a replacement for backups. Accidental changes or deletions may also be replicated to other members.
A replica set is a group of MongoDB instances that maintain the same data set and coordinate through replication and elections.
Replica Set
|
---------------------------
| | |
Primary Secondary Secondary
| | |
Writes Data Copy Data Copy
This diagram illustrates a common three-member replica set. The primary receives writes, and secondary members replicate the primary's operations.
Secondary members can serve certain reads if the application uses an appropriate read preference. By default, MongoDB reads from the primary.
| Member | Purpose |
|---|---|
| Primary | Normally receives write operations. |
| Secondary | Replicates operations from the primary. |
| Arbiter | Votes in elections but does not maintain a copy of the data set. |
| Hidden member | A secondary hidden from normal client discovery and unsuitable for ordinary application reads. |
An arbiter can participate in elections, but it cannot replace a data-bearing member or provide a copy of the data. Production deployments should be designed carefully around voting members, failure tolerance, and data redundancy.
Replication does not guarantee zero data loss or uninterrupted availability in every failure scenario. Durability depends on settings such as write concern and on the health of the replica set.
You can practise replication locally by running multiple MongoDB server processes on the same computer, each using a different data directory and port.
Example directory structure:
mongodb-replica/
node1/
node2/
node3/
For this beginner example, use a development machine, keep the test server private, and do not use production data.
The following commands assume MongoDB Server is installed
and mongod is available in your PATH.
Run each server in a separate terminal.
Terminal 1 – First member:
mkdir -p ./mongodb-replica/node1
mongod \
--replSet rs0 \
--port 27017 \
--dbpath ./mongodb-replica/node1 \
--bind_ip localhost
Terminal 2 – Second member:
mkdir -p ./mongodb-replica/node2
mongod \
--replSet rs0 \
--port 27018 \
--dbpath ./mongodb-replica/node2 \
--bind_ip localhost
Terminal 3 – Third member:
mkdir -p ./mongodb-replica/node3
mongod \
--replSet rs0 \
--port 27019 \
--dbpath ./mongodb-replica/node3 \
--bind_ip localhost
These shell commands use Unix-style syntax. On Windows, create the directories manually or use the appropriate PowerShell commands, and ensure each process has a writable data directory.
These are local practice instances without authentication. Keep them bound to localhost and never expose them to an untrusted network. A production replica set needs suitable access controls and internal member authentication.
Connect to the first member using MongoDB Shell:
mongosh --port 27017
Initialize the replica set:
rs.initiate({
_id: "rs0",
members: [
{ _id: 0, host: "localhost:27017" },
{ _id: 1, host: "localhost:27018" },
{ _id: 2, host: "localhost:27019" }
]
})
The _id value identifies the replica set.
Each member also has a unique numeric ID and a host
address that other members can reach.
Wait briefly for the election to complete. The first member will normally become primary in this practice setup, but the election outcome is not guaranteed.
All configured hostnames must resolve correctly and be reachable by the other members. For production deployments, use stable network addresses and follow MongoDB's security and deployment requirements.
Run the following command in the shell:
rs.status()
The output includes replica set health, member state, and replication information.
You can also check the current member's role:
db.hello()
Look for the isWritablePrimary field.
A value of true indicates that the
connected member is currently writable as primary.
To inspect the replica set configuration, run:
rs.conf()
Once the replica set has a primary, connect to the replica set and insert a test document.
mongosh "mongodb://localhost:27017,localhost:27018,localhost:27019/?replicaSet=rs0"
Then run:
use school
db.students.insertOne({
name: "Rahul Kumar",
course: "MongoDB",
city: "Aurangabad"
})
The write is sent to the primary. Secondary members replicate the operation from the primary's operation log.
With the default write concern, acknowledgment and replication timing depend on the deployment and its configuration. Do not assume every secondary has already applied a write immediately after it succeeds.
By default, MongoDB clients read from the primary.
To read from a secondary, select a suitable read
preference, such as secondary.
mongosh "mongodb://localhost:27017,localhost:27018,localhost:27019/?replicaSet=rs0&readPreference=secondary"
Then query the collection:
use school
db.students.find()
A secondary may lag behind the primary, so a secondary read may not immediately include the latest write. Use a read preference and consistency strategy suitable for the application's requirements.
If the primary becomes unavailable, eligible voting members may hold an election to choose a new primary. The application may experience a temporary interruption while the election takes place.
For example:
Before failure:
Primary -> Node 1
Secondary -> Node 2
Secondary -> Node 3
After a successful election:
Secondary -> Node 1 (unavailable)
Primary -> Node 2
Secondary -> Node 3
This is an illustrative example. The actual new primary depends on member health, voting configuration, eligibility, and election results.
Do not stop database processes on a production server to test failover unless you have an approved maintenance or testing plan. Practise with local test instances instead.
| Replication | Backup |
|---|---|
| Maintains copies across replica set members. | Stores a recoverable copy of data. |
| Supports availability and failover. | Supports recovery from accidental deletion or corruption. |
| Changes are generally replicated to other members. | A backup preserves the data captured at its backup point. |
| Does not replace a backup strategy. | Does not by itself provide automatic failover. |
rs0.rs.status().rs.conf().1. What is a MongoDB replica set?
2. Which member normally receives write operations?
3. Does replication replace independent backups?