美文网首页
golang操作mongo中的事务

golang操作mongo中的事务

作者: 彳亍口巴 | 来源:发表于2022-03-17 21:30 被阅读0次
func transaction() {
    filter := bson.M{"uin": 111, "singerid": 2}
    err := db.Client().UseSession(context.TODO(), func(sessionContext mongo.SessionContext) error {
        err := sessionContext.StartTransaction()
        collection1 := db.Collection("user")
        collection2 := db.Collection("task")
        // 插入第一个数据
        tasks := map[int32]Task{
            1: {
                ID:         1,
                Pending:    50,
                Completion: 1,
            },
            2: {
                ID:         2,
                Pending:    50,
                Completion: 1,
            },
        }
        update := bson.M{
            "$set": bson.M{"uin": 111, "singerid": 2, "tasks": tasks},
        }
        opts := options.Update().SetUpsert(true)
        _, err = collection2.UpdateOne(sessionContext, filter, update, opts)
        if err != nil {
            fmt.Println(err)
            return err
        }
        update2 := bson.M{
            "$set2": bson.M{"uin": 111, "singerid": 2, "xindongzhi": 100},
        }
        _, err = collection1.UpdateOne(sessionContext, filter, update2, opts)

        if err != nil {
            sessionContext.AbortTransaction(sessionContext)
            return err
        } else {
            sessionContext.CommitTransaction(sessionContext)
        }
        return nil
    })
    //
    if err != nil {
        fmt.Println(err)
        return
    }
    fmt.Println("事务成功")
}

相关文章

网友评论

      本文标题:golang操作mongo中的事务

      本文链接:https://www.haomeiwen.com/subject/zqjbdrtx.html