假设这是我的结构定义,
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 中的附加键 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" }