Mongodb replication (secondary server)

2019-07-08 10:02发布

问题:

I set up a master-slave replication of MongoDB by using 2 servers. The problem is I always going to assign rs.slaveOk() in slave server after inserting data in master. I want to automatically synced(no need to rs.slaveOk()) in secondary! What configurations should I need to change? Thanks !

This is my rs.conf()for master-slave replication!

> rs2:PRIMARY> rs.conf() {  "_id" : "rs2",  "version" : 3,
>   "protocolVersion" : NumberLong(1),  "members" : [       {           "_id" : 0,
>           "host" : "192.168.56.104:27017",            "arbiterOnly" : false,
>           "buildIndexes" : true,          "hidden" : false,           "priority" : 1,
>           "tags" : {
>                           },          "slaveDelay" : NumberLong(0),           "votes" : 1         },      {           "_id" : 1,          "host" : "192.168.56.106:27017",            "arbiterOnly" :
> false,            "buildIndexes" : true,          "hidden" : false,           "priority" :
> 0,            "tags" : {
>                           },          "slaveDelay" : NumberLong(0),           "votes" : 1         }   ],  "settings" : {      "chainingAllowed" : true,
>       "heartbeatIntervalMillis" : 2000,       "heartbeatTimeoutSecs" : 10,
>       "electionTimeoutMillis" : 10000,        "getLastErrorModes" : {
>                   },      "getLastErrorDefaults" : {          "w" : 1,            "wtimeout" : 0      },      "replicaSetId" : ObjectId("5a1e37704f3b7025eccaa874")   } }

回答1:

You can create a file /etc/mongorc.js and add rs.slaveOk() there. The file is being evaluated on each shell startup.

You can have a look here for more clarification.

Or, another way is to start mongo with the following command:

>mongo --port 27012 --eval "rs.slaveOk()" --shell

slaveOk() is only valid for that console session that it was executed in, so you would need to pass in a script or stay connected to the console with the --shell arguments.