Example for transactions in mongodb with GoLang

后端 未结 2 1535
傲寒
傲寒 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条回答
  •  旧时难觅i
    2021-02-01 00:15

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

提交回复
热议问题