doubei5114 2018-11-16 18:52
浏览 226

使用Golang将日期插入Mongo

I am trying to create a Golang MongoDB connector that takes in a request from a client and updates/inserts the request body into a database. An example of the request body is:

    {
        "_id": {
            "$oid": <hexOID>
        },
        "DateCreated": {
            "$date": 1460091636474
        },
        "DateModified": {
            "$date": 1542241349721
        }
    }

The current Mongo driver and BSON library I am using is the one located at github.com/globalsign/mgo/ and github.com/globalsign/mgo/bson respectively.

Whenever I try to unmarshal the above response, I get an error:

cannot parse date: "{
        \"$date\": 1460091636474
    }"

I've read around and saw some answers about creating a custom marshaller/unmarshaller but how would I go about doing that if it does solve this problem?

A subset of my code is as follows:

var update interface{}
errUpdate := bson.UnmarshalJSON(body, &update)
if errUpdate != nil {
    fmt.Println(errUpdate)
}
dbErr = collection.Update(query, update)

I keep update as an interface since the request body that is passed constantly changes and is not well-defined.

  • 写回答

1条回答 默认 最新

  • dongshi1868 2018-11-21 06:32
    关注

    First of all, the format of JSON in your example is called MongoDB Extended JSON. This is important, as you need to follow the format for extended JSON date. It's either $date with ISO-8601 string, or $date with $numberLong with Unix Epoch.

    Another note is with Update you need an update operation i.e. $set. If you're intending to replace the document, use Replace. Although replacing _id doesn't quite make sense, the example below will use Replace as assumed from the example.

    Given an example document in database as below:

    db.collection.insert({
                  "_id": ObjectId("5bf36072a5820f6e28a4736c"),
                  "Foo":1
    })
    

    An alternative to using globalsign/mgo is to use mongo-go-driver/bson package, there's a method UnmarshalExtJSON() that you could easily utilise to parse extended JSON.

    Using the current version (0.0.18), an example would be:

    import (
        "github.com/mongodb/mongo-go-driver/bson"
        "github.com/mongodb/mongo-go-driver/mongo"
    )
    
    replacement := bson.D{}
    // Example of response body
    data := `{"_id":{"$oid":"5bf36072a5820f6e28a4736c"},"DateModified":{"$date":{"$numberLong":"1542241349721"}},"DateCreated":{"$date":{"$numberLong":"1460091636474"}}}`
    
    err = bson.UnmarshalExtJSON([]byte(data), true, &replacement)
    if err != nil {
        log.Fatal(err)
    }
    query := bson.D{{"Foo", 1}}
    replaceResult, err := c.ReplaceOne(context.Background(), query, replacement)
    
    评论

报告相同问题?

悬赏问题

  • ¥15 微信会员卡接入微信支付商户号收款
  • ¥15 如何获取烟草零售终端数据
  • ¥15 数学建模招标中位数问题
  • ¥15 phython路径名过长报错 不知道什么问题
  • ¥15 深度学习中模型转换该怎么实现
  • ¥15 HLs设计手写数字识别程序编译通不过
  • ¥15 Stata外部命令安装问题求帮助!
  • ¥15 从键盘随机输入A-H中的一串字符串,用七段数码管方法进行绘制。提交代码及运行截图。
  • ¥15 TYPCE母转母,插入认方向
  • ¥15 如何用python向钉钉机器人发送可以放大的图片?