Question

I'm using mtools to spin up a replica set with 3 nodes (mlaunch --replicaset) on ports 27017, 27018, and 27019.

However I'm having difficulty actually connecting to the replica set using Dial from the mgo package. The code snippet below panics with the message no reachable servers:

type Person struct {
    Name   string `bson:"name"`
    Age    int    `bson:"age"`
}

func main() {
    session, err := mgo.Dial("localhost:27017,localhost:27018,localhost:27019")
    if err != nil {
            panic(err)
    }
    c := session.DB("mydb").C("testCollection")
    c.Insert(&Person{Name: "Foo", Age: 20})
}

How exactly does one connect to a replica set using the mgo package?

Was it helpful?

Solution

You need to run rs.initiate() to complete the initial replica set configuration. This will initiate a one member replica set. You then run rs.add() with the correct parameters for your hosts to bring the other members online.

Here's a tutorial on the process:

http://docs.mongodb.org/manual/tutorial/deploy-replica-set/

Generally a good idea that any time you are having issues with running something against mongodb from within code try to connect and do the same thing via the mongo shell - it can save you much time and effort.

To re-start this process using mlaunch you need to run it this way:

mlaunch --init --replicaset

This will initialize and launch a 3 node replica set named "replset"

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top