'Merge two MongoDB databases from old driver to official driver
I am using go and I need to merge these two databases to keep the clients happy. I have changed the go code to use the official driver but it refuses to accept time.Time.
So in short, I need to transfer this model database
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"`
}
into this model database
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"`
}
I don't have any strategies yet, but I welcome any examples with go code. I have thought about iterating through all items and changing types then saving it to new model. Both databases work perfectly.
My main problem is during decoding and rebuilding the struct. I am probably doing something wrong.
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)
}
Solution 1:[1]
Thanks to @icza and this slightly related answer here: https://stackoverflow.com/a/64419437/2912740 .
I was able to modify my code a bit and it worked. So it looks like mongo returns its own time that needs some conversion to regular time.
mytime := v["expirationDate"].(primitive.DateTime)
res.ExpirationDate = mytime.Time()
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 |
