Am trying to build transaction in mongodb with retries functionality as similar to other drivers like nodejs etc. This is my current implementation
if session, err = client.StartSession(); err != nil {
return err
}
if err = session.StartTransaction(); err != nil {
return 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 {
_ = session.AbortTransaction(sc)
return err
}
if result.MatchedCount != 1 || result.ModifiedCount != 1 {
_ = session.AbortTransaction(sc)
return error.New("no match")
}
if err = session.CommitTransaction(sc); err != nil {
_ = session.AbortTransaction(sc)
}
return nil
}); err != nil {
// what needs to be handled here?
// If its a particular error type can i retry transaction here?
// should i abort transaction here?
return err
}
session.EndSession(ctx)
If its a particular error type how can i go about retry a transaction?
Also do we need to abort transaction everytime a commit fails or returning an error will automatically cancels the transaction?
I am not able to find much examples on how to implement this right