How to use new URL from mongodb 3.6 to connect from golang

六月ゝ 毕业季﹏ 提交于 2019-11-29 17:29:19

I could only see that the code started, then nothing

As you have figured out, this is because DialInfo by default has a zero timeout. The call will block forever waiting for a connection to be established. You can also specify a timeout with:

dialInfo.Timeout = time.Duration(30)
session, err := mgo.DialWithInfo(dialInfo)

Now I am getting no reachable servers

This is because globalsign/mgo does not currently support SRV connection string URI yet. See issues 112. You can use the non-srv connection URI format (MongoDB v3.4), see a related question StackOverflow: 41173720.

You can use mongo-go-driver instead if you would like to connect using the SRV connection URI, for example:

mongoURI := "mongodb+srv://admin:password@prefix.mongodb.net/dbname?ssl=true&retryWrites=true"

client, err := mongo.NewClient(options.Client().ApplyURI(mongoURI))
if err != nil {
    log.Fatal(err)
}
ctx, cancel := context.WithTimeout(context.Background(), 3*time.Second)
defer cancel()
err = client.Connect(ctx)
defer client.Disconnect(ctx)

if err != nil {
    log.Fatal(err)
}
database := client.Database("go")
collection := database.Collection("atlas")

The above example is compatible with the current version v1.0.0

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!