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

时间:2019-04-07 01:00:33

标签: mongodb go

我正在查看与官方tutorial发行版一起提供的mongo-go-driver,并且连接示例在localhost上使用MongoDB服务器

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

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

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

但是driver examples for Atlas中没有Golang示例。

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

1 个答案:

答案 0 :(得分:1)

我将测试Atlas集群托管在AWS上,因此我想拥有与AWS流程类似的凭证管理。来自AWS credentials page

  

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

     
      
  1. 环境变量。

  2.   
  3. 共享凭据文件。

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

  6.   

因此,我想为我简单登录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!")
}

从这里开始,在我最初的问题中链接的其余教程将顺利进行。

相关问题