我有一个相当奇怪的问题,我一直在努力思考,并正在寻找一些关于最佳方法的建议。我使用mgo来过滤一个包含几种不同类型的结构的集合,并试图将其从bson.M转换为正确的结构。基本上,我希望能够过滤集合并查看每个结果,并基于转换为适当结构的公共字段。
下面是我尝试使用的结构的示例。
type Action interface {
MyFunc() bool
}
type Struct1 struct {
Id bson.ObjectId `bson:"_id,omitempty"`
Type string `bson:"type"`
Struct1Only string `bson:"struct1only"`
}
func (s Struct1) MyFunc() bool {
return true
}
type Struct2 struct {
Id bson.ObjectId `bson:"_id,omitempty"`
Type string `bson:"type"`
Struct2Only string `bson:"struct2only"`
}
func (s Struct2) MyFunc() bool {
return true
}我最初的想法是做一些类似的事情:
var result bson.M{}
err := c.Find(bson.M{nil}).One(&result)然后打开类型字段并转换为正确的结构,但老实说,我是go和mongo的新手,我相信有更好的方法来做到这一点。有什么建议吗?谢谢
发布于 2016-12-25 11:08:53
您不必将bson.M转换为struct,而是直接将struct指针传递给One函数
var struct2 Struct2
err := c.Find(bson.M{nil}).One(&struct2)如果您仍然希望将bson.M转换为struct,请使用Marshal和Unmarshal
var m bson.M
var s Struct1
// convert m to s
bsonBytes, _ := bson.Marshal(m)
bson.Unmarshal(bsonBytes, &s)https://stackoverflow.com/questions/36362457
复制相似问题