First, I have created 3 folders in C:\
c:\MongoRepl\1
c:\MongoRepl\2
c:\MongoRepl\3
I will be using port no 27007 (primary) ,27008 ,27009. I have made sure these ports are allowed incoming/outgoing in firewall.
Now, I will create a standalone mongod instance first. Then, create a database on the instance.
mongod --dbpath c:\MongoRepl\1 --port 27007 --smallfiles --oplogSize 50
open another terminal and connect to Mongod shell and import replication database
mongo --port 27007 --shell replication.js
Now, Cloed the mongod shell. Restarted Mongod instance as a replica.
mongod --replSet Mya --dbpath c:\MongoRepl\1 --port 27007 --smallfiles --oplogSize 50
You will set EMPTYConfig error.
Next, we will start two other mongod instances (secondary), we will join them to replicaset Mya
mongod --replSet Mya --dbpath c:\MongoRepl\2 --port 27008 --smallfiles --oplogSize 50
mongod --replSet Mya --dbpath c:\MongoRepl\3 --port 27009 --smallfiles --oplogSize 50
Now, we will initiate a replica from mongo us initiate command.
rs.initiate()
rs.status()
create a configuration
cfg={
_id:"Mya",
members:[
{_id:0,host:"machinename:27007"},
{_id:1,host:"machinename:27008"},
{_id:2,host:"machinename:27009"},
]
}
Initiate Replica
Check replica status on primary
rs.status()
Open termainal and start mongo
mongo --port 27008
mongo --port 27009
Read from secondary
I need to run rs.slaveOk() to read from secondary
rs.slaveOk()
Write to Primary
for(var i=0; i< 50000;i++){db.foo.insert({_id:i});sleep(i);}
While for statement is running, check on secondary rowcount
db.foo.count()
FailOver to Secondary
Run the command in Primary
rs.stepDown()
Now new primary is 27008
Now we will close Mongod instance on 27007.
rs.status()
27007 is unreachable since we shut down 27007
Reconfigure
On new primary replica. run config and rs.reconfig(cfg)
cfg={
_id:"Mya",
members:[
{_id:1,host:"machinename:27008"},
{_id:2,host:"machinename:27009"},
]
}
rs.reconfig(cfg)
Now, we have even number node.
Replica set information are stored in local db
use local
db.system.replset.find().pretty()