Home > Backend Development > Golang > How to connect mongodb in go using atlas?

How to connect mongodb in go using atlas?

WBOY
Release: 2024-02-09 20:36:20
forward
663 people have browsed it

How to connect mongodb in go using atlas?

php editor Apple will introduce you how to use Atlas to connect to MongoDB in Go language. Atlas is MongoDB's official cloud hosting service, providing a reliable distributed database solution. Through Atlas, you can easily connect to MongoDB in Go language and perform data reading and writing operations. The following will introduce you to the specific steps and code implementation in detail, so that you can better master the skills of using Atlas to connect to MongoDB in the Go language. Let’s learn with the editor!

Question content

I am experiencing a server selection timeout issue when connecting to mongodb. Any help would be greatly 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
Copy after login

The code I used to connect

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`
}
Copy after login

Workaround

I am hosting my test atlas cluster on aws, so I would like 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, the iam role for amazon ec2.

So I want to implement a verifiable environment for a simple login for my atlas example. The code below assumes that the following lines

have been issued on the command line

export mongo_pw='<Your atlas administrator user password>'

The following procedure will then verify your connection

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

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

The above is the detailed content of How to connect mongodb in go using atlas?. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:stackoverflow.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template