How to setup a replication set in MongoDB?

I just wanted to set up a replication set in MongoDB to check the behaviour of MongoDB replica set.
For this demonstration, I use MongoDB 2.2.0 and PowerShell 2.0.
First I want to create directories for MongoDB replication instances. I’m going to for a replication set with three nodes. So because of them, I need to create there MongoDB data directories.

New-Item -ItemType Directory -Path \data\
New-Item -ItemType Directory -Path \data\repDb1
New-Item -ItemType Directory -Path \data\repDb2
New-Item -ItemType Directory -Path \data\repDb3
New-Item -ItemType Directory -Path \log

Now copy MongoDB Binaries to the drive that you ran above PowerShell commands. Change directory to MongoDB bin. And create three separate configuration files in MongoDB bin folder with notepad or any other plain text editor.
  • config1.cnf
  • config2.cnf
  • config3.cnf
Create config1.cnf file with below content.

logpath=d:\log\log1.txt
dbpath=d:\data\repDb1
port=9991
replSet=samplecluster
rest=true

Create config2.cnf file with below content.

logpath=d:\log\log2.txt
dbpath=d:\data\repDb2
port=9992
replSet=samplecluster
rest=true

Create config3.cnf file with below content.

logpath=d:\log\log3.txt
dbpath=d:\data\repDb3
port=9993
replSet=samplecluster
rest=true

Now we are going to run MongoDB. For that you must go to MongoDB bin folder. And Press Shift and while you pressing shift right click on the free area. And select ‘Open command window here’




Now you will get a Command Prompt. Type below three commands on your command prompt.
start mongod –-config config1.cnf
start mongod –-config config2.cnf
start mongod –-config config3.cnf
Now you should log in to one of those MongoDB instances to initiate the MongoDB replication set. For that type below command.
mongo localhost:9991
Now you have a MongoDB shell and you can initiate replication set. Type below command to initiate the MongoDB replication set.
rs.initiate()
This command will take some time. Don’t worry most of the times it's not stuck. Then you have to add other instances to this MongoDB replication set.
rs.add(“localhost:9992”);
rs.add(“localhost:9993”);
This will return { “ok” : 1 }. If it is not please replace your machine name to “localhost”. Now it is done. Your MongoDB replication is up and running!!!

Tags

  • MongoDB
  • MongoShell
  • Mongo Shell
  • MongoDB Replication
  • MongoDB Install