MongoDB ReplicaSet Tutorial

MongoDB is a document-oriented database. One cool feature is that you can easily set up a MongoDB cluster, a Replica Set. A Replica Set has at least 3 nodes. Show here on the image from the MongoDB docu.

In a Replica Set there is always one Master! All other nodes are “SECONDARY” nodes! Write operations have always to go to the “PRIMARY” (Master) Node. Read operations can also go to SECONDARY nodes.

If you want to start a mongod process as part of a Replica Set you can use this parameters:

./bin/mongod --port <PORT> --bind_ip <IP-ADRESS> --replSet <REPL-NAME> --rest

for example:

./bin/mongod --port 1222 --bind_ip 192.168.0.101 --replSet myreplset --rest

You can do that on 3 different servers, or more if you want. Than log in into the server which should be the first PRIMARY. Here you have to start the mongo shell and initiate the replica set.

rs.initiate()

That is initiating the replica set. Now the replica set is running with 1 node. Now you have to add the other nodes.

rs.add(“192.168.0.102:1222”)
rs.add("192.168.0.102:1222")

All right. Now the replica set is running with 3 nodes. Now you can open a browser and navigate to the ip address of the PRIMARY node:

http://192.168.0.101:1222/_replSet

Because we started the mongod process with the parameter “–rest” we can see now a small web application showing us the status of our replica set. Here we should see 3 Members. 1 PRIMARY and 2 SECONDARY.

Now you can connect to the PRIMARY via the mongo shell console and add a document to the database. For example:

mongo --host 192.168.0.101 --port 1222 
> use myfirstdb
> db.users.save ( {name : "Hans"} )

If you connect now to a SECONDARY you will see the document there.

mongo --host 192.168.0.102 --port 1222 
> use myfirstdb
> db.users.find()

If the PRIMARY goes down, there is an election in the replica set. So that one of the SECONDARIES become the new PRIMARY. When the old PRIMARY is again up and running, he will sync with the other nodes and become again the current PRIMARY.

I have setup a replica set for an Ruby on Rails application. And I played around with it. I just rebooted randomly some of the nodes. But my Ruby on Rails was still available could deliver the data. That is pretty cool! 🙂

You can read more about Replica Set Configuration here: MongoDB Replica Set Configuration.

 

Published by Robert Reiz

CEO @ VersionEye. Passionated software developer since 1998.

4 thoughts on “MongoDB ReplicaSet Tutorial

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

%d bloggers like this: