英文:
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解组逻辑,将iconframe
和iconFrame
这两个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.)
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论