We would be creating mongodb as a replica set having 3 instances. One instance would be primary and the other 2 instances would be secondary.
For simplicity, I am going to have a replica set with 3 instances of mongodb running on the same server and thus to achieve this, all three mongodb instances would be running on different port numbers.
In production environment where in you have a dedicated mongodb instance running on a single server you can reuse the same port numbers.
- mkdir c:\data\server1 (datafile path for instance 1)
- mkdir c:\data\server2 (datafile path for instance 2)
- mkdir c:\data\server3 (datafile path for instance 3)
mongod --replSet s0 --dbpath c:\data\server1 --port 37017 --smallfiles --oplogSize 100
The above command associates the instance of mongodb to a replicaSet name "s0" and the starts the first instance of mongodb on port 37017 with oplogSize 100MB
mongod --replSet s0 --dbpath c:\data\server2 --port 37018 --smallfiles --oplogSize 100
The above command associates the instance of mongodb to a replicaSet name "s0" and the starts the first instance of mongodb on port 37018 with oplogSize 100MB
mongod --replSet s0 --dbpath c:\data\server3 --port 37019 --smallfiles --oplogSize 100
The above command associates the instance of mongodb to a replicaSet name "s0" and the starts the first instance of mongodb on port 37019 with oplogSize 100MB
With all the 3 instances started, these 3 instances are independent of each other currently. We would now need to group these instances as a replica set. We do this with the help of a config object.
3.a Connect to any of the mongod servers via the mongo shell. To do that open the command prompt and type.
mongo --port 37017
Once connected to the mongo shell, create a config object
var config = {"_id":"s0", members[]};
this config object has 2 attributes
3.b To Push(add) mongod instances to the members array in the config object. On the mongo shell type
config.members.push({"_id":0,"host":"localhost:37017"});
config.members.push({"_id":1,"host":"localhost:37018"});
config.members.push({"_id":2,"host":"localhost:37019"});
We assign each mongod instance an _id and an host. _id can be any unique number and the host should be the hostname of the server on which its running followed by the port number.
rs.initiate(config)
rs.status();