首頁  >  文章  >  後端開發  >  如何使用atlas在go連接mongodb?

如何使用atlas在go連接mongodb?

WBOY
WBOY轉載
2024-02-09 20:36:20604瀏覽

如何使用atlas在go連接mongodb?

php小編蘋果將為你介紹如何在Go語言中使用Atlas連接MongoDB。 Atlas是MongoDB官方的雲端託管服務,提供了可靠的分散式資料庫解決方案。透過Atlas,你可以輕鬆地在Go語言中連接MongoDB,並進行資料的讀寫操作。以下將為你詳細介紹具體的步驟和程式碼實現,讓你更能掌握在Go語言中使用Atlas連接MongoDB的技巧。跟著小編一起來學習吧!

問題內容

我在連接到 mongodb 時遇到伺服器選擇逾時問題。如有任何幫助,我們將不勝感激。

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

我用於連接的程式碼

const MONGOURL = "mongodb+srv://sai:[email protected]/?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`
}

解決方法

我在 aws 上託管我的測試 atlas 集群,因此我希望擁有與 aws 流程類似的憑證管理。從 aws 憑證頁面:

預設提供者鏈會依照下列順序尋找憑證:

  1. 環境變數。
  2. 共享憑證檔案。
  3. 如果您的應用程式在 amazon ec2 實例上執行,則為 amazon ec2 的 iam 角色。

因此,我想為我的 atlas 範例的簡單登入實現可驗證的環境。下面的程式碼假設已在命令列中發出以下行

export mongo_pw=''

然後以下程式將驗證您的連線

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!")
}

從這裡開始,我原來問題中連結的教程的其餘部分將順利進行。

以上是如何使用atlas在go連接mongodb?的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述:
本文轉載於:stackoverflow.com。如有侵權,請聯絡admin@php.cn刪除