In your previous attempts to connect to MongoDB Atlas from Go using mgo, you encountered issues with the DialInfo timeout and server reachability. Let's explore these issues and provide solutions:
The default DialInfo has a zero timeout, causing the connection establishment process to block indefinitely. To resolve this, you can explicitly set a timeout using:
dialInfo.Timeout = time.Duration(30) session, err := mgo.DialWithInfo(dialInfo)
Your concern about unreachable servers stems from mgo's lack of support for the SRV connection string URI format (MongoDB v3.4). To address this limitation, you can use the non-srv connection URI format:
mongoURI = "mongodb+srv://admin:password@my-atlas-cluster-01.mongodb.net:27017/dbname?ssl=true&retryWrites=true"
If you prefer to use SRV in your connection URI, consider utilizing the mongo-go-driver. Here's an example:
mongoURI := "mongodb+srv://admin:password@my-atlas-cluster-01.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")
Note that this code is compatible with the current version of mongo-go-driver (v1.0.0).
The above is the detailed content of How to Connect to MongoDB Atlas from Go: Solving Timeout and Server Reachability Issues?. For more information, please follow other related articles on the PHP Chinese website!