在使用 Mongo Go 驱动程序时,我想检索无模式文档。
我可以使用 bson.M
检索文档json:",inline" bson:",inline"
但这增加了额外的 "男"当我尝试解码为结构时输入 json
type Product struct {
ID primitive.ObjectID `bson:"_id"`
ProductId string `bson:"product_id" json:"product_id"`
bson.M `json:",inline" bson:",inline"`
}
输出:-{
"id":"<ObjectId>",
"M":{
"some":""
}
}
但相反,我想要它如何存储在 Mongo 中。{
"id":"<ObjectId>",
"some":""
}
我不能直接使用这样的东西,因为我想将它转换为 struct 以使用某些属性var pr bson.M
err := p.FindOne(ctx, &p.options,query, &pr)
如何删除从 Mongo 转换无模式文档时添加的额外 key ?我需要显式覆盖 MarshalJSON() 还是使用标签提供了一些东西?
最佳答案
How can I remove that extra key which is getting added while converting schemaless Documents from Mongo?
您可以只定义一个字段映射名称,在编码时将其展平。例如:
type Product struct {
ID primitive.ObjectID `bson:"_id"`
ProductId string `bson:"product_id"`
Others bson.M `bson:",inline"`
}
当您解码一个文档时,您会看到它将包含其他没有
Others
的字段。姓名。例如,如果您有一个文档:{
"_id": ObjectId("5e8d330de85566f5a0557ea4"),
"product_id": "foo",
"some": "x",
"more": "y"
}
doc := Product{}
err = cur.Decode(&doc)
fmt.Println(doc)
// Outputs
// {ObjectID("5e8d330de85566f5a0557ea4") foo map[more:y some:x]}
I cant use directly something like this as I want to cast it to struct to work with some properties
您可以直接将其用于查询谓词。例如:
// After decoding 'doc' to product
var result bson.M
err := collection.FindOne(context.TODO(), doc).Decode(&result)
使用 MongoDB Go driver 测试v1.3.2
更新:
如果你想返回 JSON,你可以使用 bson.MarshalExtJSON() .在处理 JSON 中不存在的对象方面,这也应该更容易。即对象ID。例如:
// After decoding 'doc' to product
ejson, err := bson.MarshalExtJSON(doc, true, false)
fmt.Println(string(ejson))
关于mongodb - Go Mongo Driver 检索无模式文档,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61086720/