golang mongodb 迁移数据库 library mongo 到 mgo

golang mongodb migrate database library mongo to mgo

我想将数据库的库从 github.com/mongodb/mongo-go-driver/mongo 更改为 github.com/globalsign/mgo,我的问题是我不知道如何为新库转换此代码:

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),
    )

我当前的代码:

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

我如何转换这个 options.Update().SetUpsert(true) 以便在新库中使用?

只需使用 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}},
)

引自 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.