登录
首页 >  Golang >  Go问答

MongoDB Atlas集群中Golang插入结构切片接口已被取消,当前拓扑

来源:stackoverflow

时间:2024-03-22 12:54:59 378浏览 收藏

在 MongoDB Atlas 集群中使用 Golang 插入结构切片接口时,遇到 "服务器选择错误:上下文已取消" 的错误。代码将结构体切片转换为接口切片并尝试插入集合。错误表明当前拓扑结构没有主副本,服务器类型未知。确保 IP 已列入白名单,指定上下文,并尝试使用 context.todo() 或在连接关闭后使用 defer。

问题内容

当我将一组文档插入 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)
    }

}

正确答案


信息不充分。检查 ip 是否已列入白名单。还要指定您正在使用的上下文。您可以尝试使用 context.todo()

我试过了,效果很好。

确保您的连接成功。还可以使用 defer 关闭连接。

这是您可以尝试的示例代码:

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

为了更好地理解,请参阅此链接:https://raw.githubusercontent.com/mongodb/docs-golang/master/source/includes/usage-examples/code-snippets/insertMany.go

今天关于《MongoDB Atlas集群中Golang插入结构切片接口已被取消,当前拓扑》的内容介绍就到此结束,如果有什么疑问或者建议,可以在golang学习网公众号下多多回复交流;文中若有不正之处,也希望回复留言以告知!

声明:本文转载于:stackoverflow 如有侵犯,请联系study_golang@163.com删除
相关阅读
更多>
最新阅读
更多>
课程推荐
更多>