如何使用官方的mongo-go-driver连接到MongoDB Atlas



我正在查看与官方mongo-go-driver一起发布的教程,连接示例在localhost上使用MongoDB服务器

// Set client options
clientOptions := options.Client().ApplyURI("mongodb://localhost:27017")

但是,新的托管MongoDB服务Atlas需要用户名和密码才能登录。连接字符串采用以下格式

mongodb://[username:password@]host1[/[database][?options]]

但在 Atlas 的驱动程序示例中没有 Golang 示例。

所以我想知道,登录 Atlas 而不将密码硬编码到将发布在 Github 上的源文件中的最佳方法是什么?

我在 AWS

上托管我的测试 Atlas 集群,因此我希望对 AWS 流程进行类似的凭证管理。从 AWS 凭证页面:

默认提供程序链按以下顺序查找凭据:

  1. 环境变量。

  2. 共享凭据文件。

  3. 如果您的应用程序在 Amazon EC2 实例上运行,则为 Amazon EC2 的 IAM 角色。

因此,我想为我的简单登录 Atlas 示例实现可验证的环境。 下面的代码假定已在命令行发出以下行

export MONGO_PW='<your Atlas admin user password>'

然后以下程序将验证您的连接

package main
import (
    "context"
    "fmt"
    "os"
    "go.mongodb.org/mongo-driver/mongo"
    "go.mongodb.org/mongo-driver/mongo/options"
)
var username = "<username>"
var host1 = "<atlas host>"  // of the form foo.mongodb.net
func main() {
    ctx := context.TODO()
    pw, ok := os.LookupEnv("MONGO_PW")
    if !ok {
        fmt.Println("error: unable to find MONGO_PW in the environment")
        os.Exit(1)
    }
    mongoURI := fmt.Sprintf("mongodb+srv://%s:%s@%s", username, pw, host1)
    fmt.Println("connection string is:", mongoURI)
    // Set client options and connect
    clientOptions := options.Client().ApplyURI(mongoURI)
    client, err := mongo.Connect(ctx, clientOptions)
    if err != nil {
        fmt.Println(err)
        os.Exit(1)
    }
    err = client.Ping(ctx, nil)
    if err != nil {
        fmt.Println(err)
        os.Exit(1)
    }
    fmt.Println("Connected to MongoDB!")
}

从这里开始,我原始问题中链接的教程的其余部分进展顺利。

最新更新