当前位置: > > > > MongoDB Go 驱动程序无法正确解组嵌套文档
来源:stackoverflow
2024-04-21 12:45:41
0浏览
收藏
今日不肯埋头,明日何以抬头!每日一句努力自己的话哈哈~哈喽,今天我将给大家带来一篇《MongoDB Go 驱动程序无法正确解组嵌套文档》,主要内容是讲解等等,感兴趣的朋友可以收藏或者有更好的建议在评论提出,我都会认真看的!大家一起进步,一起学习!
问题内容
我有一个对集合中的特定字段进行操作的 setter 和 getter。 setter 工作正常并且文档按预期更新,但是 getter 无法正确返回填充的结构。 我做错了什么?
作为 go 结构的集合:
type model struct { id primitive.objectid `bson:"_id,omitempty"` entitytype string `bson:"entity_type,omitempty"` entityid string `bson:"entity_id,omitempty"` configsource configsources `bson:"config_source,inline,omitempty"` } type configsources struct { configs []configsource `bson:"configs,omitempty"` } type configsource struct { hour int `bson:"hour"` source string `bson:"source"` }
设置器片段:
cfg := configsources{ configs: []configsource{ { hour: 1, source: "hour_1_source", }, { hour: 2, source: "hour_2_source", }, }, } c := db.collection("foo") selectorquery := bson.m{"entity_id": entityid} updatequery := bson.m{"$set": bson.m{"config_source": configname}} result, err := c.updatemany(ctx, selectorquery, updatequery)
getter 代码片段:
c := db.collection("foo") q, err := c.find(ctx, bson.m{"_id": bson.m{"$in": idsimquerying}}) if err != nil { return nil } var results []model err = q.all(ctx, &results) fmt.printf("\n\n\n\n%#v\n\n\n\n", results) // this output is shown below
得到的结果:
[]Model{ Model{ ID:primitive.ObjectID{0x5a, 0xa9, 0x7a, 0x40, 0xdf, 0xe5, 0x90, 0x44, 0x49, 0xdb, 0x61, 0x4}, EntityType:"CELL", EntityID:"4110902605985611776", ConfigSource:ConfigSources{ Configs:[]ConfigSource(nil) } } }
atlas 中查看的字段:
解决方案
一旦我从模型结构中删除内联,它就工作正常
type Model struct { ID primitive.ObjectID `bson:"_id,omitempty"` EntityType string `bson:"entity_type,omitempty"` EntityID string `bson:"entity_id,omitempty"` ConfigSource ConfigSources `bson:"config_source,omitempty"` }
今天关于《MongoDB Go 驱动程序无法正确解组嵌套文档》的内容介绍就到此结束,如果有什么疑问或者建议,可以在公众号下多多回复交流;文中若有不正之处,也希望回复留言以告知!