Home >>MongoDB Tutorial >MongoDB Replication
The process of synchronizing data through several servers is replication. With several copies of data on various database servers, replication provides consistency and improves the availability of data. Replication defends a database from a single server 's loss. Replication also helps you to recover from failure of hardware and interruptions of service. You may dedicate one to disaster recovery, reporting, or backup, with additional copies of the data.
By using the replica set, MongoDB achieves replication. A replica set is a group of instances of Mongod holding the same set of data. One node is a primary node in a replica that receives all writing operations. All other cases, such as secondary ones, apply primary operations so that they have the same collection of data. The replica set can only contain a single primary node.
A standard MongoDB replication diagram is shown in which the client application always interacts with the primary node and then replicates the data to the secondary nodes from the primary node.
We'll convert the standalone MongoDB instance to a replica set in this tutorial. To convert to the replica set, the steps below are
mongod --port "PORT" --dbpath "YOUR_DB_DATA_PATH" --replSet "REPLICA_SET_INSTANCE_NAME"
Example
mongod --port 27017 --dbpath "D:\set up\mongodb\data" --replSet rs0
Start the Mongod instances on multiple machines to add members to a replica set. Open a Mongo client now and issue an rs.add() command.
Syntax
The basic syntax of rs.add() command is as follows −
>rs.add(HOST_NAME:PORT)
Example
Suppose your name for the Mongod instance is mongod1.net and runs on port 27017. Use the rs.add() command in the Mongo client to add this instance to the replica set.
>rs.add("mongod1.net:27017") >
You can only add the Mongod instance to the replica collection when you are connected to the primary node. Use the db.isMaster() command in the mongo client to check if you are connected to the primary or not.