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条)

报告相同问题?

悬赏问题

  • ¥15 装 pytorch 的时候出了好多问题,遇到这种情况怎么处理?
  • ¥20 IOS游览器某宝手机网页版自动立即购买JavaScript脚本
  • ¥15 手机接入宽带网线,如何释放宽带全部速度
  • ¥30 关于#r语言#的问题:如何对R语言中mfgarch包中构建的garch-midas模型进行样本内长期波动率预测和样本外长期波动率预测
  • ¥15 ETLCloud 处理json多层级问题
  • ¥15 matlab中使用gurobi时报错
  • ¥15 这个主板怎么能扩出一两个sata口
  • ¥15 不是,这到底错哪儿了😭
  • ¥15 2020长安杯与连接网探
  • ¥15 关于#matlab#的问题:在模糊控制器中选出线路信息,在simulink中根据线路信息生成速度时间目标曲线(初速度为20m/s,15秒后减为0的速度时间图像)我想问线路信息是什么