简体   繁体   中英

golang mongodb migrate database library mongo to 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 ?

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM