dongtan8532 2019-05-09 08:05 采纳率: 0%
浏览 63
已采纳

使用_t定义查询C#驱动程序插入的记录

I want to query data which was inserted by C# mongodriver with polymorhism. The query will be done by Golang driver. Structure of the data is shown below. I want to map _t to structs, in other words, I want to apply polymorhism to record in Go. Is it possible to do it in Golang mongo drivers? The list of structs is below as well.

One record example from mongo collection

{"_id" : "asdasda12312312asdasda",
"structure" : [ 
                    {
                        "_t" : "AObject",
                        "Text" : "asdasdasda",
                        "State" : "asdasda"
                    }, 
                    {
                        "_t" : "BObject",
                        "Number" : "123",
                    }, 
                    {
                        "_t" : "CObject",
                        "Testing" : "Pompeo"
                    }
                ]
}

Go Structs

type Data struct{
  _id string
  Structure []Object
}

type Object interface{
}

type AObject struct {
  Text  string
  State string 
}
type BObject struct {
  Number  string 
}
type CObject struct {
  Testing  string
}

Thanks

  • 写回答

2条回答 默认 最新

  • douao2000 2019-05-09 09:29
    关注

    What mongo driver are you using? "_t" is a parameter used to determine what type was serialized if the current type is different than the nominal type. It's also used for normal JSON serialization so you have one of three ways I can think of.

    1. Using different GO mongo driver which supports it. I would suggest using https://github.com/mongodb/mongo-go-driver which is official MongoDB Go Driver
    2. Write switch / case statement to deserialize it yourself
    type MongoObject struct {
            // Contains all fields from all objects
            _t string
            Text string
            State string
            Number string
            Testing string
    }
    
    func DeserializeObject(object MongoObject) Object{
            switch t {
            case "AObject":
            return &AObject{Text: object.Text, State: object.State}
            case "BObject":
            return &BObject{Number: object.Text}
            case "CObject":
            return &CObject{Testing: object.Testing}
        }
    }
    
    1. You can get data from mongo as JSON and use certain marshaling to do it for you
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥50 如何用脚本实现输入法的热键设置
  • ¥20 我想使用一些网络协议或者部分协议也行,主要想实现类似于traceroute的一定步长内的路由拓扑功能
  • ¥30 深度学习,前后端连接
  • ¥15 孟德尔随机化结果不一致
  • ¥15 apm2.8飞控罗盘bad health,加速度计校准失败
  • ¥15 求解O-S方程的特征值问题给出边界层布拉休斯平行流的中性曲线
  • ¥15 谁有desed数据集呀
  • ¥20 手写数字识别运行c仿真时,程序报错错误代码sim211-100
  • ¥15 关于#hadoop#的问题
  • ¥15 (标签-Python|关键词-socket)