MongoDB - Replication

The following ports are configured for primary and secondary servers

 
  Port 27018 – Primary 
  Port 27019 – Secondary 
  Port 27020 – Secondary 

Replicaset Name

 
  Replica Set name is satish

Create three directories to store the data of the instances

 
Create three Directories to store three mongod instances data  in c:\data folder
rs1,rs2 and rs3

Assign Port numbers and log files path

 
start mongod -replSet satish -logpath \data\rs1\1.log  --dbpath \data\rs1  --port 27018  
Assigning port number and log file path to the secondary server
start mongod -replSet satish -logpath \data\rs2\2.log  --dbpath \data\rs2  --port 27019  
start mongod -replSet satish -logpath \data\rs3\3.log  --dbpath \data\rs3  --port 27020  

Interconnect all nodes

 

mongo --port 27018
  
  config = {_id:"satish",members:[
  {_id:0,host:"localhost:27018"},
  {_id:1,host:"localhost:27019"},
  {_id:2,host:"localhost:27020"}]};
Output Screen Shot is given below
interconnection of nodes images

intiate config using the command below

 
  > rs.initiate(config)
  { "ok" : 1 }

Check the Status

 
satish:OTHER> rs.status()
Output Screen Shot is given below
interconnection of nodes images

Writing data to Primary Server

 

  satish:PRIMARY> db.createCollection("students");
  { "ok" : 1 }
  
  satish:PRIMARY> db.students.insert({"name":"satish","located":"primary"});
  WriteResult({ "nInserted" : 1 })

Check if the data was replicated in the secondary

 
  mongo --port 27019
  satish:SECONDARY> rs.slaveOk();
  satish:SECONDARY> db.students.find().pretty()
  {
          "_id" : ObjectId("58bfaf6f6abc83e6c2c4feae"),
          "name" : "satish",
          "located" : "primary"
  }

Checking if data was replicated in another secondary node in port 27020

 
  mongo --port 27020
  satish:SECONDARY> rs.slaveOk();
  satish:SECONDARY> db.students.find().pretty();
  {
          "_id" : ObjectId("58bfaf6f6abc83e6c2c4feae"),
          "name" : "satish",
          "located" : "primary"
  }

You cannot insert data in secondary node

 
  satish:SECONDARY> db.students.insert({"name":"badrecord"});
  WriteResult({ "writeError" : { "code" : 10107, "errmsg" : "not master" } })
  satish:SECONDARY>

Failover in Replication

 
  If the primary server goes down then secondary server becomes primary 

Shutting down primary server

 
  satish:PRIMARY> use admin
  switched to db admin
  satish:PRIMARY> db.shutdownServer();