-
Notifications
You must be signed in to change notification settings - Fork 155
Transactions
- Version of mongoDB server >= v4.0
- Topology of mongoDB server should be replica set
- You can use transactions:
callback := func(sessCtx context.Context) (interface{}, error) {
// Important: make sure the sessCtx used in every operation in the whole transaction
if _, err := cli.InsertOne(sessCtx, bson.D{{"abc", int32(1)}}); err != nil {
return nil, err
}
if _, err := cli.InsertOne(sessCtx, bson.D{{"xyz", int32(999)}}); err != nil {
return nil, err
}
return nil, nil
}
result, err = cli.DoTransaction(ctx, callback)
- At the same time, you can create session and use session to start transaction: (Don't forget to call EndSession if session is not used anymore)
s, err := cli.Session()
defer s.EndSession(ctx)
callback := func(sessCtx context.Context) (interface{}, error) {
// Important: make sure the sessCtx used in every operation in the whole transaction
if _, err := cli.InsertOne(sessCtx, bson.D{{"abc", int32(1)}}); err != nil {
return nil, err
}
if _, err := cli.InsertOne(sessCtx, bson.D{{"xyz", int32(999)}}); err != nil {
return nil, err
}
return nil, nil
}
_, err = s.StartTransaction(ctx, callback)
-
Make sure all operations in transaction use the sessCtx as context parameter
-
Don't forget to call EndSession after action is done, if you create session yourself.
-
Timeout: If operations in transaction takes more than(include equal) 120s, the operations will not take effect
-
Retry: If operations in transaction return qmgo.ErrTransactionRetry, the whole transaction will retry, so this transaction must be idempotent.
check TestSession_RetryTransAction in retry example
-
If the ctx parameter already has a Session attached to it, it will be replaced by this session.
-
In MongoDB 4.2 and earlier, you cannot create collections in transctions. Write operations that result in document inserts (e.g. insert or update operations with upsert: true) must be on existing collections if run inside transactions.
-
Starting in MongoDB 4.4, you can create collections in transactions implicitly or explicitly. You must use MongoDB drivers updated for 4.4, however. See Create Collections and Indexes In a Transaction for details.