英文:
bson.M to struct
问题
我有一个相当奇怪的问题,我一直在努力理解,并寻求一些指导,以找到最佳方法。我正在使用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{}).One(&result)
然后根据类型字段进行切换,并将其转换为正确的结构体,但老实说,我对Go和Mongo都很陌生,我相信有更好的方法来做到这一点。有什么建议吗?谢谢。
英文:
I have a fairly odd question that I have been trying to wrap my head around and am looking of some pointers as to the best approach. I am use mgo to filter a collection that contains a few different types of structs and am trying to cast from bson.M to the proper struct after the fact. Basically I'd like to be able to filter the collection and look at each result and based on a common field cast to the proper struct.
Here is sample of the structs I am trying to use.
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
}
My initial idea was to do something like:
var result bson.M{}
err := c.Find(bson.M{nil}).One(&result)
Then switch on the type field and cast to the proper struct, but honestly I am new to go and mongo and am sure there is better way to do this. Any suggestions? Thanks
答案1
得分: 31
你不需要将bson.M转换为结构体,而是直接将结构体指针传递给One函数。
var struct2 Struct2
err := c.Find(bson.M{nil}).One(&struct2)
如果你仍然想将bson.M转换为结构体,可以使用Marshal和Unmarshal。
var m bson.M
var s Struct1
// 将m转换为s
bsonBytes, _ := bson.Marshal(m)
bson.Unmarshal(bsonBytes, &s)
英文:
You don't have to convert bson.M to struct, instead, you directly pass a struct pointer to the One function
var struct2 Struct2
err := c.Find(bson.M{nil}).One(&struct2)
In case of you still want to convert bson.M to struct, use Marshal and Unmarshal
var m bson.M
var s Struct1
// convert m to s
bsonBytes, _ := bson.Marshal(m)
bson.Unmarshal(bsonBytes, &s)
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论