mongodb官方的golang驱动基础使用
//不能在单节点使用(副本集可以)
func UseSession(client *mongo.Client) {
client.UseSession(getContext(), func(sctx mongo.SessionContext) error {
err := sctx.StartTransaction(options.Transaction().
SetReadConcern(readconcern.Snapshot()).
SetWriteConcern(writeconcern.New(writeconcern.WMajority())),
)
if err != nil {
return err
}
_, err = client.Database("aa").Collection("bb").InsertOne(sctx, bson.D{{"aa", 3}})
if err != nil {
_ = sctx.AbortTransaction(sctx)
return err
}
_, err = client.Database("aa").Collection("bb").InsertOne(sctx, bson.D{{"bb", 3}})
if err != nil {
_ = sctx.AbortTransaction(sctx)
return err
}
for {
err = sctx.CommitTransaction(sctx)
switch e := err.(type) {
case nil:
return nil
case mongo.CommandError:
if e.HasErrorLabel("UnknownTransactionCommitResult") {
continue
}
return e
default:
return e
}
}
})
}