【问题标题】:Merge two MongoDB databases from old driver to official driver将两个 MongoDB 数据库从旧驱动程序合并到官方驱动程序
【发布时间】:2022-02-20 23:06:23
【问题描述】:

我正在使用 go,我需要合并这两个数据库以使客户满意。我已将 go 代码更改为使用官方驱动程序,但它拒绝接受 time.Time
所以简而言之,我需要转移这个模型数据库

MgoResults struct {
        ID             bson.ObjectId  `bson:"_id"`
        ZipID          string         `bson:"zid"`
        Message        string         `bson:"message"`
        Result         string         `bson:"res"`
        Error          error          `bson:"errors"`
        ExpirationDate time.Time      `bson:"expirationDate"`
    }

进入这个模型数据库

MgoResults struct {
        ID             primitive.ObjectID  `bson:"_id"`
        ZipID          string              `bson:"zid"`
        Message        string              `bson:"message"`
        Result         string              `bson:"res"`
        Error          error               `bson:"errors"`
        ExpirationDate primitive.DateTime  `bson:"expirationDate"`
    }

我还没有任何策略,但我欢迎任何带有 go 代码的示例。 我考虑过遍历所有项目并更改类型,然后将其保存到新模型中。两个数据库都运行良好。

我的主要问题是在解码和重建结构期间。我可能做错了什么。

    var v bson.M
    err = result.Decode(&v)

    if err != nil {
        log.Println("error at decode result : ", err)
    }
    //start filling the struct
    res.ZipID = v["zid"].(string)
    if v["errors"] == nil{
        res.Error = nil
    }else{
        res.Error = v["errors"].(error)
    }

    res.Message= v["message"].(string)
    res.ID      = v["_id"].(primitive.ObjectID)
    res.Result  = v["res"].(string)
    if v["expirationDate"] == nil{
        //res.ExpirationDate = time.Now()
    }else{
        res.ExpirationDate = v["expirationDate"].(time.Time )
        //res.ExpirationDate = v["expirationDate"].(primitive.DateTime)
    }

【问题讨论】:

  • 官方驱动应该使用time.Time,支持。
  • 谢谢,@icza,我正急于完成这个。到目前为止它确实有效。那么,我应该能够在旧的现有数据库上使用新代码吗?
  • 只需将bson.ObjectId 替换为primitive.ObjectID,但time.Time 应该保留。
  • 我已经做到了。谢谢。
  • 我会尝试调查这个错误的来源,"interface conversion: interface {} is primitive.DateTime, not time.Time"

标签: mongodb go


【解决方案1】:

感谢@icza 和这个稍微相关的答案:https://stackoverflow.com/a/64419437/2912740

我能够稍微修改一下我的代码并且它起作用了。所以看起来 mongo 返回了它自己的time,需要一些转换为常规的time

mytime := v["expirationDate"].(primitive.DateTime)
res.ExpirationDate = mytime.Time()

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-03-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-04-02
    相关资源
    最近更新 更多