golang操作mongo中的事务

2022-03-17  本文已影响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("事务成功")
}
上一篇 下一篇

猜你喜欢

热点阅读