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)
}
}
CodePudding user response:
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