登录
首页 >  Golang >  Go问答

如何将结构体数组插入 MongoDB

来源:stackoverflow

时间:2024-04-02 19:39:33 258浏览 收藏

亲爱的编程学习爱好者,如果你点开了这篇文章,说明你对《如何将结构体数组插入 MongoDB》很感兴趣。本篇文章就来给大家详细解析一下,主要介绍一下,希望所有认真读完的童鞋们,都有实质性的提高。

问题内容

我正在尝试使用 go.mongodb.org/mongo-driver 库将存储在结构数组中的数据插入到 mongodb 中。我的结构是

type statement struct {
    productid        string `bson:"product_id" json:"product_id"`
    modelnum         string `bson:"model_num" json:"model_num"`
    title            string `bson:"title" json:"title"`
}

我的插入代码是

func insert(stmts []Statement) {
    client, err := mongo.NewClient(options.Client().ApplyURI("mongodb://127.0.0.1:27017"))
    if err != nil {
        log.Fatal(err)
    }
    ctx, _ := context.WithTimeout(context.Background(), 10*time.Second)
    err = client.Connect(ctx)
    if err != nil {
        log.Fatal(err)
    }
    defer client.Disconnect(ctx)

    quickstartDatabase := client.Database("quickstart")
    testCollection := quickstartDatabase.Collection("test")
    testCollection.InsertMany(ctx, stmts) // This is giving error
}

编译器给出错误 cannot use stmts ([]statement 类型的变量) as []interface{} value in the argument to testcollection.insertmany at insertmany 命令。

我已经尝试在插入之前使用 bson.marshal 编组结构,但即使这样也不起作用。如何将此数据插入数据库?


解决方案


insertmany 接受 []接口{}

我会这样做

newValue := make([]interface{}, len(statements))

for i := range statements {
  newValue[i] = statements[i]
}

col.InsertMany(ctx, newValue)

今天关于《如何将结构体数组插入 MongoDB》的内容介绍就到此结束,如果有什么疑问或者建议,可以在golang学习网公众号下多多回复交流;文中若有不正之处,也希望回复留言以告知!

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