MongoDB Tutorial - MongoDB Replication

Replication is the process of synchronizing data across multiple servers.

MongoDB uses replica set to do replication.

A replica set is a group of MongoDB instances that host the same data set.

In a replica set one node is primary node that receives all write operations. All other instances receives operations from the primary so that they have the same data set.

Replica set can have only one primary node.

Replica set must have minimum 3 nodes.

In a replica set one node is primary node and remaining nodes are secondary.

All data replicates from primary to secondary node.

In case of failing, a new primary node is elected.

After the recovery of failed node, it again join the replica set and works as a secondary node.

Set up a replica set

Convert standalone mongod instance to a replica set, start the mongodb server by specifying --replSet option.

The basic syntax of --replSet is given below:

mongod --port "PORT" --dbpath "YOUR_DB_DATA_PATH" --replSet "REPLICA_SET_INSTANCE_NAME"

The following code shows how to create a replica set.

mongod --port 27017 --dbpath "D:\mongodb\data" --replSet rs0

It starts a mongod instance with the name rs0, on port 27017.

To initiate a new replica set, in mongo client issue the command rs.initiate().

To check the replica set configuration, issue the command rs.conf().

To check the status of replica sete, issue the command rs.status().

Add members to replica set

To add members to replica set, start mongod instances on multiple machines. Now start a mongo client and issue a command rs.add().

The following code shows the basic syntax of rs.add() command.


Suppose the mongod instance name is and it is running on port 27017. To add this instance to replica set issue the command rs.add() in mongo client.


We can add mongod instance to replica set only when connecting to primary node.

To check whether we are connected to primary, use db.isMaster() command in mongo client.