登录
首页 >  Golang >  Go问答

在MongoDB中动态结构字段的文档插入

来源:stackoverflow

时间:2024-02-28 11:09:21 272浏览 收藏

今日不肯埋头,明日何以抬头!每日一句努力自己的话哈哈~哈喽,今天我将给大家带来一篇《在MongoDB中动态结构字段的文档插入》,主要内容是讲解等等,感兴趣的朋友可以收藏或者有更好的建议在评论提出,我都会认真看的!大家一起进步,一起学习!

问题内容

我正在尝试使用 go 插入 mongodb,其中一个字段将包含动态数据。就我而言,它将通过 grpc 来自其他服务,但我将示例简化为:

package main

import (
    "context"
    "fmt"
    _struct "github.com/golang/protobuf/ptypes/struct"
    "go.mongodb.org/mongo-driver/bson/primitive"
    "go.mongodb.org/mongo-driver/mongo"
    "go.mongodb.org/mongo-driver/mongo/options"
    "log"
)

type siteItem struct {
    ID   primitive.ObjectID `bson:"_id,omitempty"`
    Name string             `bson:"name"`

    // Data string     `bson:"data"`
    Data *_struct.Value `bson:"data"`
}

func main() {
    client, _ := mongo.NewClient(options.Client().ApplyURI("mongodb://localhost:27017"))
    client.Connect(context.TODO())
    collection := client.Database("site").Collection("sites")

    data := siteItem{
        Name: "Test name",

        // Data: "Test data",
        Data: &_struct.Value{
            Kind: &_struct.Value_StringValue{
                StringValue: "String from struct",
            },
        },
    }

    res, err := collection.InsertOne(context.Background(), data)
    if err != nil {
        log.Fatal(err)
    }

    fmt.Println(res)
}

我收到错误:cannot 将类型 main.siteitem 转换为 bson 文档:找不到 structpb.isvalue_kind 的编码器

如果我使用 string 而不是 *_struct.value - 它工作得很好。但就我而言,data: 可能具有来自 json 的任何值。


解决方案


解决这个问题的一种方法是使用 bson 标记来标记结构,但这并不总是可行。我根据具体情况使用以下方法之一处理此案例:

  • 使用 map[string]接口{} 和 json 封送处理:
type Item struct {
   Data map[string]interface{} `bson:"data"`
}

...
// Writing to db
data,_:=json.Marshal(someStruct)
json.Unmarshal(data,&item.Data)
// Reading from db
data,_:=json.Marshal(item.Data)
json.Unmarshal(data,&result.Data)
  • 通过将 data 声明为 string 而不是 map[string]interface{} 来存储原始 json 数据

理论要掌握,实操不能落!以上关于《在MongoDB中动态结构字段的文档插入》的详细介绍,大家都掌握了吧!如果想要继续提升自己的能力,那么就来关注golang学习网公众号吧!

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