重新定义Golang中的bson标签,如何与数据库中具有小写字段名的字段兼容?

huangapple go评论76阅读模式
英文:

Redefine the bson tag in golang, how to be compatible with the fields in the database with lowercase field names?

问题

有很多类似这样的结构(大约有数百个结构,全部由工具自动生成):

type ChatInfo struct {
	Name         string `json:"name"`
	IconFrame    uint64 `json:"iconFrame"`
}

bson标签被遗漏了,导致数据库中的字段名变成了小写形式,像这样:

{
    "name" : "myname",
    "iconframe" :101
}

现在,我想添加bson标签:

type ChatInfo struct {
	Name         string `json:"name" bson:"name"`
	IconFrame    uint64 `json:"iconFrame" bson:"iconFrame"`
}

但是当我从数据库中读取数据时,发现IconFrame字段的值为0。

我想找到一种方法来保持与原始的小写字段名的兼容性。由于有大量的数据且存储有些混乱,修改数据库中的数据并不是非常实际。

谢谢。

英文:

There are many structures(There are roughly hundreds of structures, all generated automatically by a tool.) like this:

type ChatInfo struct {
	Name         string `json:"name"`
	IconFrame    uint64 `json:"iconFrame"`
}

The bson tag was forgotten, causing the field name in the database to become lowercase.
Like this:

{
    "name" : "myname",
    "iconframe" :101
}

Now, I want to add the bson tag:

type ChatInfo struct {
	Name         string `json:"name" bson:"name"`
	IconFrame    uint64 `json:"iconFrame" bson:"iconFrame"`
}

But when I read the data from the database, I find that the value of the IconFrame field is 0.

I want to find a way to maintain compatibility with the original lowercase field names. Because there is a lot of data and the storage is somewhat disorganized, it is not very practical to modify the data in the database.

Thanks.

答案1

得分: 1

你可以实现自定义的BSON解组逻辑,将iconframeiconFrame这两个MongoDB字段解码到ChatInfo.IconFrame字段中,但是这个自定义逻辑会在所有文档解码时运行!

你肯定不希望有这种不必要的开销。最简单的方法是重命名MongoDB中现有的字段。你只需要运行几个更新操作,然后就可以永远使用新的字段名了。

例如,要将iconframe字段重命名为iconFrame,可以使用以下命令:

db.chatinfo.updateMany(
  {"iconframe": {$exists: true}},
  {$rename: {"iconframe": "iconFrame"}}
)

(过滤条件部分甚至可以为空,因为不存在的字段不会被更新。)

英文:

You could implement custom BSON unmarshaling logic that decodes both iconframe and iconFrame MongoDB fields into the ChatInfo.IconFrame field, but that custom logic would run in all document decoding!

You simply don't want that unnecessary overhead. Simplest is to rename existing fields in MongoDB. You just have to run a few update operations once, and then you'll be good to go forever.

For example, to rename the iconframe field to iconFrame, use this:

db.chatinfo.updateMany(
  {"iconframe": {$exists: true}},
  {$rename: {"iconframe": "iconFrame"}}
)

(The filter part may even by empty as non-existing fields will not be updated.)

huangapple
  • 本文由 发表于 2022年12月9日 16:42:54
  • 转载请务必保留本文链接:https://go.coder-hub.com/74740658.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定