[英]While inserting nested document in MongoDB, its inserting the nested document with an id. Why is that happening and how to stop that?
[英]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 解组返回
{
"_id": ObjectID,
"key": "...",
"value": "..."
}
如何摆脱 MongoDB 中的额外关键部分内容?
首先,您需要导出结构字段,否则驱动程序将跳过这些字段。
如果您不想在 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" }
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.