doulan8846 2016-04-01 17:33
浏览 120

bson.M构建

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条回答

  • douzhao7445 2016-12-25 03:08
    关注

    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)
    
    评论

报告相同问题?

悬赏问题

  • ¥15 LiBeAs的带隙等于0.997eV,计算阴离子的N和P
  • ¥15 关于#windows#的问题:怎么用WIN 11系统的电脑 克隆WIN NT3.51-4.0系统的硬盘
  • ¥15 来真人,不要ai!matlab有关常微分方程的问题求解决,
  • ¥15 perl MISA分析p3_in脚本出错
  • ¥15 k8s部署jupyterlab,jupyterlab保存不了文件
  • ¥15 ubuntu虚拟机打包apk错误
  • ¥199 rust编程架构设计的方案 有偿
  • ¥15 回答4f系统的像差计算
  • ¥15 java如何提取出pdf里的文字?
  • ¥100 求三轴之间相互配合画圆以及直线的算法