Home > Backend Development > Golang > How to Connect to MongoDB Atlas from Go Using the Latest Drivers?

How to Connect to MongoDB Atlas from Go Using the Latest Drivers?

Barbara Streisand
Release: 2024-12-05 01:37:09
Original
341 people have browsed it

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>
<div class="code" style="position:relative; padding:0px; margin:0px;"><pre class="brush:php;toolbar:false">panic(err)
Copy after login

}
dialInfo.Timeout = time.Duration(30)
session, err := mgo.DialWithInfo(dialInfo)
if err != nil {

println("error")
log.Fatal(err)
Copy after login

}

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>
<div class="code" style="position:relative; padding:0px; margin:0px;"><div class="code" style="position:relative; padding:0px; margin:0px;"><pre class="brush:php;toolbar:false">log.Fatal(err)
Copy after login
Copy after login

}
ctx, cancel := context.WithTimeout(context.Background(), 3*time.Second)
defer cancel()
err = client.Connect(ctx)
if err != nil {

log.Fatal(err)
Copy after login
Copy after login

}
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!

source:php.cn
Previous article:Why Do Different Field Orders in Go Structs Result in Varying Sizes? Next article:How to Reliably Create an Empty Text File in Go?
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Latest Issues
Related Topics
More>
Popular Recommendations
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template