Home >Backend Development >Golang >How to Connect to MongoDB Atlas from Go Using the Latest Drivers?
MongoDB 3.6 URI Connection from Go
Q: How to connect to MongoDB Atlas using golang drivers in the latest versions of MongoDB?
Go drivers in versions 3.6 no longer support the SRV connection URI format by default. Instead, users should use the non-SRV connection URI format.
Fix:
<br>mongoURI := "mongodb://admin:[email protected]:27017/dbname"</p> <p>dialInfo, err := mgo.ParseURL(mongoURI)<br>if err != nil {</p> <pre class="brush:php;toolbar:false">panic(err)
}
dialInfo.Timeout = time.Duration(30)
session, err := mgo.DialWithInfo(dialInfo)
if err != nil {
println("error") log.Fatal(err)
}
Q: Getting "no reachable servers" error
This issue occurs because globalsign/mgo does not support SRV connection string URI yet.
Fix:
Use mongo-go-driver instead to connect using the SRV connection URI:
<br>mongoURI := "mongodb srv://admin:[email protected]/dbname?ssl=true&retryWrites=true"</p> <p>client, err := mongo.NewClient(options.Client().ApplyURI(mongoURI))<br>if err != nil {</p> <pre class="brush:php;toolbar:false">log.Fatal(err)
}
ctx, cancel := context.WithTimeout(context.Background(), 3*time.Second)
defer cancel()
err = client.Connect(ctx)
if err != nil {
log.Fatal(err)
}
defer client.Disconnect(ctx)
database := client.Database("go")
collection := database.Collection("atlas")
Note: Update the mongo-go-driver to version 1.0.0 or above for compatibility with the example provided.
The above is the detailed content of How to Connect to MongoDB Atlas from Go Using the Latest Drivers?. For more information, please follow other related articles on the PHP Chinese website!