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 delta降尺度计算的一些细节,有偿
  • ¥15 Arduino红外遥控代码有问题
  • ¥15 数值计算离散正交多项式
  • ¥30 数值计算均差系数编程
  • ¥15 redis-full-check比较 两个集群的数据出错
  • ¥15 Matlab编程问题
  • ¥15 训练的多模态特征融合模型准确度很低怎么办
  • ¥15 kylin启动报错log4j类冲突
  • ¥15 超声波模块测距控制点灯,灯的闪烁很不稳定,经过调试发现测的距离偏大
  • ¥15 import arcpy出现importing _arcgisscripting 找不到相关程序