【发布时间】:2022-01-24 07:39:14
【问题描述】:
当我将一组文档插入 MongoDB Atlas 集合时,我收到以下错误消息:
2021/12/23 09:37:03 服务器选择错误:上下文已取消,当前拓扑:{类型:ReplicaSetNoPrimary,服务器:[{地址:cluster-attitude-shard-00-00.o7pjk.mongodb .net:27017,类型:未知},{地址:cluster-attitude-shard-00-01.o7pjk.mongodb.net:27017,类型:未知},{地址:cluster-attitude-shard-00-02.o7pjk .mongodb.net:27017,类型:未知},]}
我使用下一个代码:
interfaz_slice := ToInterfaceSlice(students)
_, err := coleccion.InsertMany(ctx, interfaz_slice)
函数“ToInterfaceSlice”接收一个结构切片并返回一个接口切片
我不明白我在哪里犯了错误
提前致谢
问题的新部分:
文件片段“main.go”:
func main() {
var students []data.TypeStudent
absPath, _ := filepath.Abs("data/students.csv")
students = data.LeerFichero(absPath)
data.ConectaBD()
data.InsertaColleccionEstudiantes(students)
}
文件片段“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
}
文件片段“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)
}
}
【问题讨论】:
-
错误不在 Golang 客户端代码中,而是在您正在运行的 MongoDB 集群中。您是否尝试过连接 mongo shell 并执行查询?
-
我可以连接 mongosh:link
-
我看了视频,你应该从 mongo shell 运行相同的查询,并请分享其余代码、连接处理程序等。
标签: go mongodb-atlas