2019-04-07 01:00
浏览 328

您如何使用官方的mongo-go-driver连接到MongoDB Atlas [重复]

This question already has an answer here:

I'm looking at the tutorial offered in conjunction with the release of the official mongo-go-driver and the connection example uses a MongoDB server on localhost

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

However, the new hosted MongoDB service Atlas requires username and password to login. The connection string takes the format


but there is no Golang example in the driver examples for Atlas.

So I'm wondering, what is the best way to log into Atlas without hard coding a password into a source file that will be posted on Github?


图片转代码服务由CSDN问答提供 功能建议

此问题已经存在 在这里有答案

  • 写回答
  • 好问题 提建议
  • 追加酬金
  • 关注问题
  • 邀请回答

1条回答 默认 最新

  • dsarttv037029 2019-04-07 01:00

    I am hosting my test Atlas cluster on AWS so I wanted to have similar credential management to the AWS process. From the AWS credentials page:

    The default provider chain looks for credentials in the following order:

    1. Environment variables.

    2. Shared credentials file.

    3. If your application is running on an Amazon EC2 instance, IAM role for Amazon EC2.

    Therefore, I wanted to implement the environment veriable for my simple login to Atlas example. Code below assumes that the following line has been issued at the command line

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

    Then the following program will verify your connection

    package main
    import (
    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")
        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 {
        err = client.Ping(ctx, nil)
        if err != nil {
        fmt.Println("Connected to MongoDB!")

    From here the rest of the tutorial linked in my original question goes smoothly.

    解决 无用
    打赏 举报

相关推荐 更多相似问题