将bson.M转换为struct。

huangapple go评论76阅读模式
英文:

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)

huangapple
  • 本文由 发表于 2016年4月2日 01:33:58
  • 转载请务必保留本文链接:https://go.coder-hub.com/36362457.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定