Step by Step MongoDB Replication setup on Windows

In this article, we will see Step by Step MongoDB Replication setup on Windows. We are going to add 1 Primary and 2 Secondary servers to replica Set.

What is replication?
Replication is a way of keeping identical copies of data on multiple servers and it is recommended for all production deployments.

Step by Step MongoDB Replication setup on Windows1

Primary Server: Making standalone as primary server with no: 27017
Secondary Servers: Started two servers with port numbers: 27020 and 27021(I am configuring replication on single machine). If you are configuring replcation on 3 different hosts, then provide name of host and port no when required in coming steps.

Step by Step MongoDB Replication setup on Windows

Important Notes: Before going to setup MongoDB replication, please take backup all important.

1. Start standalone server as shown below.

mongod --dbpath "C:\Program Files\MongoDB\Server\4.0\data" --logpath "C:\Program Files\MongoDB\Server\4.0\log\mongod.log" --port 27017 --storageEngine=wiredTiger --journal --replSet r2schools

2. Connect to the server with port number 27017

mongo --port 27017

3. Then, create variable rsconf.

rsconf={_id:"r2schools",members:[{_id:0,host:"localhost:27017"}]} rs.initiate(rsconf)

Note: Here i am configuring replication on single windows machine. If you have three different machines, then localhost with name or IP address and port number.

4. Start secondary server on the port 27020.

mongod --dbpath "C:\data1\db" --logpath "C:\data1\log\mongod.log" --port 27020 --storageEngine=wiredTiger --journal --replSet r2schools

5. Logon to secondary server.

mongo --port 27020

6. Start secondary server on the port 27021.

mongod --dbpath "C:\data2\db" --logpath "C:\data2\log\mongod.log" --port 27021 --storageEngine=wiredTiger --journal --replSet r2schools

7. Logon to secondary server.

mongo --port 27021

8. Run the following commands on Primary server.

rs.add("localhost:27020") rs.add("localhost:27020")

9. Now go to secondary servers and run below command on both the secondary servers.

rs.slaveOk()

Replication Setup verification:

Create a collection primary server and verify this change will reflect on secondary servers or not.

1. Connect to primary server.

use ecom

2. Create a collection in Primary

db.test.insert({name:"MongoDB"})

1. Now connect to secondary servers and check the list of the database by running command

show dbs

2. Switch to the newly created database.

use ecom

3. run the command against ecom database.

db.test.find().pretty().

So in this article, we covered how to setup MongoDB replication on Windows and then verified replication status.

Watch the video tutorials for the same:

Leave a Reply

Your email address will not be published. Required fields are marked *