Home > Backend Development > Golang > How to Connect to MongoDB Atlas from Go using the Updated `mongodb srv` URL Syntax?

How to Connect to MongoDB Atlas from Go using the Updated `mongodb srv` URL Syntax?

Linda Hamilton
Release: 2024-12-07 15:21:13
Original
934 people have browsed it

How to Connect to MongoDB Atlas from Go using the Updated `mongodb srv` URL Syntax?

Connecting to MongoDB Atlas from Go Using New URL Syntax

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)
    }
}
Copy after login

Note:

If you encounter a "no reachable servers" error, ensure that:

  • You are using a valid MongoDB Atlas connection URI with the correct credentials.
  • You are using a Go driver compatible with MongoDB 3.6 or later.

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!

source:php.cn
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template