0

When I insert a set of documents into a MongoDB Atlas collection I get the following error message:

2021/12/23 09:37:03 server selection error: context canceled, current topology: { Type: ReplicaSetNoPrimary, Servers: [{ Addr: cluster-attitude-shard-00-00.o7pjk.mongodb.net:27017, Type: Unknown }, { Addr: cluster-attitude-shard-00-01.o7pjk.mongodb.net:27017, Type: Unknown }, { Addr: cluster-attitude-shard-00-02.o7pjk.mongodb.net:27017, Type: Unknown }, ] }

I use the next code:

interfaz_slice := ToInterfaceSlice(students)

_, err := coleccion.InsertMany(ctx, interfaz_slice)

The function "ToInterfaceSlice" recieve a slice of structs and return a slice of interface

I do not understand where I am making a mistake

Thanks in advance

New part of question:

File fragment "main.go":

func main() {

    var students []data.TypeStudent

    absPath, _ := filepath.Abs("data/students.csv")

    students = data.LeerFichero(absPath)

    data.ConectaBD()

    data.InsertaColleccionEstudiantes(students)

}

File fragment "students.go":

type TypeStudent struct {
    FirstName string `bson:"first_name" json:"first_name"`
    LastName  string `bson:"last_name" json:"last_name"`
    Class     string `bson:"class" json:"class"`
}

func ToInterfaceSlice(lista []TypeStudent) []interface{} {
    iface := make([]interface{}, len(lista))
    for i := range lista {
        iface[i] = lista[i]
    }
    return iface
}

File fragment "basedatos.go":

func ConectaBD() {

    cliente_local, err := mongo.NewClient(options.Client().ApplyURI(cadena_conexion))
    if err != nil {
        log.Fatal(err)
    }
    ctx, cancelar = context.WithTimeout(context.Background(), 10*time.Second)
    err = cliente_local.Connect(ctx)
    if err != nil {
        log.Fatal(err)
    }
    defer cancelar()

    mongo_cliente = cliente_local.Database("attitude")

    log.Println("[+]Connected to MongoDB Atlas")

}

func InsertaColleccionEstudiantes(students []TypeStudent) {

    coleccion = mongo_cliente.Collection("students")

    interfaz_slice := ToInterfaceSlice(students)

    log.Println("[+]A slice of interfaces are inserted directly into MONGODB")

    _, err := coleccion.InsertMany(ctx, interfaz_slice)

    if err != nil {
        log.Fatal(err)
    }

}
3
  • 1
    The error is not in the Golang client code, but in the MongoDB cluster you're running. Have you tried connecting with mongo shell and executing the query? Commented Dec 23, 2021 at 9:28
  • I could connect with mongosh: link Commented Dec 23, 2021 at 9:58
  • I watched the video, you should run the same query from mongo shell, and please share the rest of the code, the connection handler, etc. Commented Dec 23, 2021 at 10:01

1 Answer 1

1

Information is not sufficient. Check if IP is whitelisted or not. Also specify which context you are using. You can try with context.TODO().

I tried and it's working fine.

Make sure your connection is successful. Also close the connection using defer.

Here is the sample code you can try with this :

client, err := mongo.Connect(context.TODO(), options.Client().ApplyURI(uri))
    if err != nil {
        panic(err)
    }
    defer func() {
        if err = client.Disconnect(context.TODO()); err != nil {
            panic(err)
        }
    }()

    // begin insertMany
    coll := client.Database("insertDB").Collection("haikus")
    docs := []interface{}{
        bson.D{{"title", "Record of a Shriveled Datum"}, {"text", "No bytes, no problem. Just insert a document, in MongoDB"}},
        bson.D{{"title", "Showcasing a Blossoming Binary"}, {"text", "Binary data, safely stored with GridFS. Bucket the data"}},
    }

    result, err := coll.InsertMany(context.TODO(), docs)
    if err != nil {
        panic(err)
    }

For better understanding please refer this link : https://raw.githubusercontent.com/mongodb/docs-golang/master/source/includes/usage-examples/code-snippets/insertMany.go

Sign up to request clarification or add additional context in comments.

2 Comments

your fragment of code works. I have to have any wrong in my code
Amazing, just to add context.TODO works:_, err := coleccion.InsertMany(context.TODO(), interfaz_slice). Thank you so much and merry christmas!!!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.