我想将数据库库从 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()
方法而不是 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.
关于mongodb - golang mongodb migrate database 库 mongo 到 mgo,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55072565/