Example for transactions in mongodb with GoLang

后端 未结 2 1526
傲寒
傲寒 2021-02-01 00:03

I need an example to implement transactions in MongoDB with GoLang.

I\'m using this golang driver for mongodb

https://github.com/mongodb/mongo-go-driver

2条回答
  •  情歌与酒
    2021-02-01 00:08

    It can be confusing. Below is a simple example.

    if session, err = client.StartSession(); err != nil {
        t.Fatal(err)
    }
    if err = session.StartTransaction(); err != nil {
        t.Fatal(err)
    }
    if err = mongo.WithSession(ctx, session, func(sc mongo.SessionContext) error {
        if result, err = collection.UpdateOne(sc, bson.M{"_id": id}, update); err != nil {
            t.Fatal(err)
        }
        if result.MatchedCount != 1 || result.ModifiedCount != 1 {
            t.Fatal("replace failed, expected 1 but got", result.MatchedCount)
        }
    
        if err = session.CommitTransaction(sc); err != nil {
            t.Fatal(err)
        }
        return nil
    }); err != nil {
        t.Fatal(err)
    }
    session.EndSession(ctx)
    

    You can view full examples here.

提交回复
热议问题