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 docker实践项目
  • ¥15 数电几道习题,写出作答过程,ai一律不采用
  • ¥15 利用pthon计算薄膜结构的光导纳
  • ¥15 海康hlss视频流怎么播放
  • ¥15 Paddleocr:out of memory error on GPU
  • ¥30 51单片机C语言数码管驱动单片机为AT89C52
  • ¥100 只改动本课件的 cal_portfolio_weight_series(decision_date), 跑完本课件。设计一个信息比率尽量高的策略。
  • ¥20 如何在visual studio 2022中添加ImageMagick库
  • ¥50 如何实现uniapp编译的微信小程序做可回溯视频
  • ¥15 求Houdini使用行家,付费。价格面议。