To work with MongoDB replication at first create 3 MongoDB server. You can use VM or Docker containers for each server. I have set up 3 VM with the MongoDB server.
Here my three mongo collection URI is:
mongodb://192.168.33.10:27017
mongodb://192.168.33.11:27017
mongodb://192.168.33.12:27017
Update mongodb configuration (/etc/mongod.conf) file for each server and update bindIp to 0.0.0.0 so that MongoDB become accessable from outsite of the VM.
And add the following line for enabling replica set. Here rs0 is the name of replica set.
replication:
replSetName: "rs0"
Finally new configuration file:
# mongod.conf
# for documentation of all options, see:
# http://docs.mongodb.org/manual/reference/configuration-options/
# Where and how to store data.
storage:
dbPath: /var/lib/mongodb
journal:
enabled: true
# engine:
# mmapv1:
# wiredTiger:
# where to write logging data.
systemLog:
destination: file
logAppend: true
path: /var/log/mongodb/mongod.log
# network interfaces
net:
port: 27017
bindIp: 0.0.0.0
# how the process runs
processManagement:
timeZoneInfo: /usr/share/zoneinfo
#security:
#operationProfiling:
replication:
replSetName: "rs0"
#sharding:
## Enterprise-Only Options:
#auditLog:
#snmp:
Go to mongo shell and check replica set.
mongo
rs.status()
you will get following output:
{
"operationTime" : Timestamp(0, 0),
"ok" : 0,
"errmsg" : "no replset config has been received",
"code" : 94,
"codeName" : "NotYetInitialized",
"$clusterTime" : {
"clusterTime" : Timestamp(0, 0),
"signature" : {
"hash" : BinData(0,"AAAAAAAAAAAAAAAAAAAAAAAAAAA="),
"keyId" : NumberLong(0)
}
}
}
Login to your primary VM and go to mongo shell and run the following command:
rs.initiate( {
_id : "rs0",
members: [
{ _id: 0, host: "192.168.33.10:27017" },
{ _id: 1, host: "192.168.33.11:27017" },
{ _id: 2, host: "192.168.33.12:27017" }
]
})
Replace the IP address according to your MongoDB server IP address.
Check replica set status:
rs.status()
You will get all the replication information.
Login to replica set:
mongo 'mongodb://192.168.33.10:27017,192.168.33.11:27017,192.168.33.10:27017/?replicaSet=rs0'
Print Replication Information:
rs.printReplicationInfo()
Show replica set configuration:
rs.conf()
Now create a new collection on the primary server:
db.createCollection("helloworld")
Now login to another secondary VM:
Run the following command to fix the error:
rs.secondaryOk()
Use secondary replica for reading data:
mongo 'mongodb://192.168.33.10:27017,192.168.33.11:27017,192.168.33.10:27017/?replicaSet=rs0&readPreference=secondary'