duanhe8280
duanhe8280
2019-01-28 09:08

使用GoLang在mongodb中进行交易的示例

已采纳

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

There is no clear documentation for how to implement transactions.

Can anyone help me?

  • 点赞
  • 写回答
  • 关注问题
  • 收藏
  • 复制链接分享
  • 邀请回答

2条回答

  • duanju6788 duanju6788 2年前

    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.

    点赞 评论 复制链接分享
  • douqian3712 douqian3712 2年前

    This will help you

    ctx := context.Background()
    client, err := mongo.Connect(ctx, options.Client().ApplyURI("mongodb://localhost:27017"))
    if err != nil {
        panic(err)
    }
    
    db := client.Database("testdb")
    defer db.Client().Disconnect(ctx)
    col := db.Collection("testcol")
    
    // transaction
    err = db.Client().UseSession(ctx, func(sessionContext mongo.SessionContext) error {
        err := sessionContext.StartTransaction()
        if err != nil {
            fmt.Println(err)
            return err
        }
    
        _, err = col.InsertOne(sessionContext, bson.M{"_id": "1", "name": "berry"})
        if err != nil {
            fmt.Println(err)
            return err
        }
    
        _, err = col.InsertOne(sessionContext, bson.M{"_id": "2", "name": "gucci"})
        if err != nil {
            sessionContext.AbortTransaction(sessionContext)
            fmt.Println(err)
            return err
        } else {
            sessionContext.CommitTransaction(sessionContext)
        }
        return nil
    })
    
    点赞 评论 复制链接分享

相关推荐