Query:
How do I connect to MongoDB Atlas using the updated mongodb srv URL syntax in the latest versions of Go drivers?
Solution:
Previously, the Go driver used a custom URL parser for connecting to MongoDB Atlas. However, in MongoDB 3.6, the native Go url.Parse function is used for parsing the new URL format:
package main import ( "context" "log" "time" "go.mongodb.org/mongo-driver/bson" "go.mongodb.org/mongo-driver/mongo" "go.mongodb.org/mongo-driver/mongo/options" ) func main() { mongoURI := "mongodb+srv://admin:[email protected]/dbname?ssl=true&retryWrites=true" // Set a timeout for connection establishment. ctx, cancel := context.WithTimeout(context.Background(), 3*time.Second) defer cancel() // Use mongo-go-driver to connect to Atlas. client, err := mongo.NewClient(options.Client().ApplyURI(mongoURI)) if err != nil { log.Fatal(err) } if err = client.Connect(ctx); err != nil { log.Fatal(err) } defer client.Disconnect(ctx) // Now you can perform database operations as usual. database := client.Database("go") collection := database.Collection("atlas") err = collection.InsertOne(ctx, bson.M{"username": "testuser"}) if err != nil { log.Fatal(err) } }
Note:
If you encounter a "no reachable servers" error, ensure that:
The above is the detailed content of How to Connect to MongoDB Atlas from Go using the Updated `mongodb srv` URL Syntax?. For more information, please follow other related articles on the PHP Chinese website!