Is it possible to run replica set commands like rs.initiate()
and rs.add()
using mgo driver from a golang application?
If yes, how??
Is it possible to run replica set commands like rs.initiate()
and rs.add()
using mgo driver from a golang application?
If yes, how??
Thanks to @alex-blex's answer which gave me the start. But this is what finally worked for me:
session, err := mgo.Dial("rs1.example.net?connect=direct")
if err != nil {
panic(err)
}
defer session.Close()
session.SetMode(mgo.Monotonic, true)
config := bson.M{
"_id": "my_replica_set",
"members": []bson.M{
{"_id": 0, "host": "rs1.example.net:27017"},
{"_id": 1, "host": "rs2.example.net:27017", "priority": 2},
{"_id": 2, "host": "rs3.example.net", "arbiterOnly": true},
},
}
result := bson.M{}
if err := session.Run(bson.M{"replSetInitiate": config}, &result); err != nil {
panic(err)
}
Notice the following:
?connect=direct
in the connection string.
If not specified, the connection will timeout, probably because the replica set has not been initialized yet.
session.SetMode(mgo.Monotonic, true)
Session mode should be monotonic
as the default session used by mgo is primary
which performs all operations on primary. Since the replica set has not been initialized yet, there wont be a primary and the operation (in this case, replSetInitiate
) will just timeout
"_id": "my_replica_set"
in the config
For this to work, the mongo servers will have to be started with the replica set name my_replica_set
. One way of doing that would be:
mongod --replSet my_replica_set