如何摆脱在 mongodb 中插入嵌套结构时添加的附加键
How to get rid of an additional key added while inserting a nested struct in mongodb
假设这是我的结构定义,
type partialContent struct {
key string `json:"key" bson"key"`
value string `json:"value" bson:"value"`
}
type content struct {
id string `json:"id" bson:"_id,omitempty"`
partialContent
}
在 MongoDB 中存储 内容 时,它存储为
{
"_id": ObjectID,
"partialcontent": {
"key": "...",
"value": "..."
}
}
但是 JSON 解组 returns
{
"_id": ObjectID,
"key": "...",
"value": "..."
}
如何删除 MongoDB 中的附加键 partialcontent?
首先,您需要导出结构字段,否则驱动程序将跳过这些字段。
如果您不想在 MongoDB 中嵌入文档,请使用 ,inline
bson 标签选项:
type PartialContent struct {
Key string `json:"key" bson"key"`
Value string `json:"value" bson:"value"`
}
type Content struct {
ID string `json:"id" bson:"_id,omitempty"`
PartialContent `bson:",inline"`
}
正在插入这个值:
v := Content{
ID: "abc",
PartialContent: PartialContent{
Key: "k1",
Value: "v1",
},
}
将在 MongoDB 中生成此文档:
{ "_id" : "abc", "key" : "k1", "value" : "v1" }
假设这是我的结构定义,
type partialContent struct {
key string `json:"key" bson"key"`
value string `json:"value" bson:"value"`
}
type content struct {
id string `json:"id" bson:"_id,omitempty"`
partialContent
}
在 MongoDB 中存储 内容 时,它存储为
{
"_id": ObjectID,
"partialcontent": {
"key": "...",
"value": "..."
}
}
但是 JSON 解组 returns
{
"_id": ObjectID,
"key": "...",
"value": "..."
}
如何删除 MongoDB 中的附加键 partialcontent?
首先,您需要导出结构字段,否则驱动程序将跳过这些字段。
如果您不想在 MongoDB 中嵌入文档,请使用 ,inline
bson 标签选项:
type PartialContent struct {
Key string `json:"key" bson"key"`
Value string `json:"value" bson:"value"`
}
type Content struct {
ID string `json:"id" bson:"_id,omitempty"`
PartialContent `bson:",inline"`
}
正在插入这个值:
v := Content{
ID: "abc",
PartialContent: PartialContent{
Key: "k1",
Value: "v1",
},
}
将在 MongoDB 中生成此文档:
{ "_id" : "abc", "key" : "k1", "value" : "v1" }