MongoDB Replica Set

Going from development to production with mongoDB you would probably want to set up replica sets for your database. In this post, I will show you how to set up a simple database with tree member replica sets.

If you do not have mongoDB installed, you can follow this post to see how I prefer to set things up running mongoDB in multiple versions.

Since I am going to run tree mongoDB instances on the same machine in this demo, I will have to create tree data directories and run them on different ports.


Now you can start the tree instances of mongoDB like this:


Make sure you use the same replica set name on all tree.

The next step is to initiate the replica set by typing “C:\mongodb-3.2.8\bin\mongo.exe –port 30001” to connect and type “rs.initiate()” to initiate the replica set. Click Enter and Enter again.


In this case, I am running all replica sets on one server. It will enter the primary but the two others are also running.

Next step is to add a secondary. You can do this by editing the configuration file or in a simple rs.add() function: rs.add(“[Server Name]:[port])


If you now type “rs.config()” you will get the current configuration.


From my setup, you can see that I have two servers running now. One on port 30001 and a second on port 30003.

The third server I want to set up as an Arbiter. To do this you need to do a “rs.add(“servername:port”, true)”. I you look at the properties on the configuration now you can see that we have a third server up and running on port 30002 with “arbiterOnly=true”


To have a deeper look into what is set up you can type “rs.status()”. You will see the server’s state, what server is the primary and the secondary and witch server that is synchronizing to and so on.


*Press “Ctrl+L” if you want to clear the screen.


Now that we have our replica sets up and running, we can see some replication in action. Do an insert on the primary server and check that you actually have data saved. (You can only write data to the primary server in a replica set)


To check the replication you have to connect to the secondary server. Do this by “db = connect(servername:port/databasename)”. You will see that the prompt will show that you are connected to the secondary.


To read data from the secondary you will have to tell for security reasons that this is ok. Type “db.setSlaveOk()” and start you queries. If you get the same data here as in the primary then replication is working.


Thanks for readning.

One thought on “MongoDB Replica Set

Comments are closed.