how to connect with mongodb in go using atlas?

huangapple go评论85阅读模式
英文:

how to connect with mongodb in go using atlas?

问题

我在连接到MongoDB时遇到了服务器选择超时的问题。希望能得到帮助。

> 选择错误:服务器选择超时,当前拓扑结构:{ 类型:ReplicaSetNoPrimary,服务器:[{ 地址:ac-pjyudwq-shard-00-01.1bnb2bm.mongodb.net:27017,类型:未知,最后错误:拨号tcp 3.6.207.111:27017:i/o超时 },{ 地址:ac-pjyudwq-shard-00-00.1bnb2bm.mongodb.net:27017,类型:未知,最后错误:拨号tcp 3.7.150.83:27017:i/o超时 },{ 地址:ac-pjyudwq-shard-00-02.1bnb2bm.mongodb.net:27017,类型:未知,最后错误:拨号tcp 3.7.137.42:27017:i/o超时 },] } 退出状态1

我用于连接的代码如下:

const MONGOURL = "mongodb+srv://sai:sai@cluster0.1bnb2bm.mongodb.net/?retryWrites=true&w=majority"

var collection *mongo.Collection

func init() {
    fmt.Println("在init函数中")
    var databasename string = "GOAPI"
    var collectionname string = "Movies"
    client, err := mongo.Connect(context.TODO(), options.Client().ApplyURI(MONGOURL))
    if err != nil {
        fmt.Println("无法获取Mongo连接")
        log.Fatal(err)
    }
    collection = client.Database(databasename).Collection(collectionname)
    fmt.Println("成功创建集合")
    doc := Movie{
        Name:    "rrr",
        Watched: false,
        Rating:  9,
        Id:      "12121",
    }
    result, err := collection.InsertOne(context.Background(), doc)
    if err != nil {
        log.Fatal("无法插入数据", err)
    }
    fmt.Println("成功添加:", result.InsertedID)

    // mongo.Connect()的代码
}

希望对你有所帮助。

英文:

I am getting a server selection timeout while connecting to mongodb.Any help is appreciated.

> selection error: server selection timeout, current topology: { Type:
> ReplicaSetNoPrimary, Servers: [{ Addr:
> ac-pjyudwq-shard-00-01.1bnb2bm.mongodb.net:27017, Type: Unknown, Last
> error: dial tcp 3.6.207.111:27017: i/o timeout }, { Addr:
> ac-pjyudwq-shard-00-00.1bnb2bm.mongodb.net:27017, Type: Unknown, Last
> error: dial tcp 3.7.150.83:27017: i/o timeout }, { Addr:
> ac-pjyudwq-shard-00-02.1bnb2bm.mongodb.net:27017, Type: Unknown, Last
> error: dial tcp 3.7.137.42:27017: i/o timeout }, ] } exit status 1

Code that I used for the connection

const MONGOURL = "mongodb+srv://sai:sai@cluster0.1bnb2bm.mongodb.net/?retryWrites=true&w=majority"

var collection *mongo.Collection

func init() {
    fmt.Println("in the init function") var databasename string = "GOAPI"
    var collectionname string = "Movies"
    client, err: = mongo.Connect(context.TODO(), options.Client().ApplyURI(MONGOURL)) if err != nil {
        fmt.Println("unable to get mongo connection ") log.Fatal(err)
    }
    collection = ( * mongo.Collection)(client.Database(databasename).Collection(collectionname)) fmt.Println("sucessfully collection is created ") doc: = Movie {
        Name: "rrr",
        Watched: false,
        Rating: 9,
        Id: "12121"
    }
    result, err: = collection.InsertOne(context.Background(), doc) if err != nil {
        log.Fatal("hey unable to insert one ", err)
    }
    fmt.Println("sucessfully added : ", result.InsertedID)

    // mongo.Connect()`your text`
}

答案1

得分: 0

我正在托管我的测试Atlas集群在AWS上,所以我希望有类似的凭证管理方式来与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!")
}

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

英文:

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=&#39;&lt;your Atlas admin user password&gt;&#39;

Then the following program will verify your connection

package main

import (
    &quot;context&quot;
    &quot;fmt&quot;
    &quot;os&quot;

    &quot;go.mongodb.org/mongo-driver/mongo&quot;
    &quot;go.mongodb.org/mongo-driver/mongo/options&quot;
)

var username = &quot;&lt;username&gt;&quot;
var host1 = &quot;&lt;atlas host&gt;&quot;  // of the form foo.mongodb.net

func main() {

    ctx := context.TODO()

    pw, ok := os.LookupEnv(&quot;MONGO_PW&quot;)
    if !ok {
        fmt.Println(&quot;error: unable to find MONGO_PW in the environment&quot;)
        os.Exit(1)
    }
    mongoURI := fmt.Sprintf(&quot;mongodb+srv://%s:%s@%s&quot;, username, pw, host1)
    fmt.Println(&quot;connection string is:&quot;, 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(&quot;Connected to MongoDB!&quot;)
}

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

huangapple
  • 本文由 发表于 2023年2月1日 19:41:43
  • 转载请务必保留本文链接:https://go.coder-hub.com/75309661.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定