douxu2467 2019-03-08 23:51
浏览 188
已采纳

golang mongodb将数据库库mongo迁移到mgo

I want to change library for database from github.com/mongodb/mongo-go-driver/mongo to github.com/globalsign/mgo, my problem is I dont know how convert this code for new library :

import "github.com/mongodb/mongo-go-driver/mongo/options"
res, err := s.totals().UpdateOne(ctx,
        bson.M{"contract_id": cID, "date": date},
        bson.M{"$inc": bson.M{"value": value}},
        options.Update().SetUpsert(true),
    )

My current code :

collection := s.totals()
err := collection.Update(
    bson.M{"contract_id": contractID, "date": date},
    bson.M{"$inc": bson.M{"value": value}},
    //options.Update().SetUpsert(true),
)

How i can convert this options.Update().SetUpsert(true) for use in new library ?

  • 写回答

1条回答 默认 最新

  • douhuan1908 2019-03-09 00:23
    关注

    Simply use the Collection.Upsert() method instead of Collection.Update():

    info, err := collection.Upsert(
        bson.M{"contract_id": contractID, "date": date},
        bson.M{"$inc": bson.M{"value": value}},
    )
    

    Quoting from the doc of Collection.Upsert():

    Upsert finds a single document matching the provided selector document and modifies it according to the update document. If no document matching the selector is found, the update document is applied to the selector document and the result is inserted in the collection.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 Visual Studio问题
  • ¥15 state显示变量是字符串形式,但是仍然红色,无法引用,并显示类型不匹配
  • ¥20 求一个html代码,有偿
  • ¥100 关于使用MATLAB中copularnd函数的问题
  • ¥20 在虚拟机的pycharm上
  • ¥15 jupyterthemes 设置完毕后没有效果
  • ¥15 matlab图像高斯低通滤波
  • ¥15 针对曲面部件的制孔路径规划,大家有什么思路吗
  • ¥15 钢筋实图交点识别,机器视觉代码
  • ¥15 如何在Linux系统中,但是在window系统上idea里面可以正常运行?(相关搜索:jar包)