Transactions
On this page
Overview
In this guide, you can learn how to use the MongoDB Go Driver to perform transactions. Transactions allow you to run a series of operations that do not change any data until the transaction is committed. If any operation in the transaction returns an error, the driver cancels the transaction and discards all data changes before they ever become visible.
In MongoDB, transactions run within logical sessions. A session is a grouping of related read or write operations that you intend to run sequentially. Sessions enable causal consistency for a group of operations or allow you to execute operations in an ACID transaction. MongoDB guarantees that the data involved in your transaction operations remains consistent, even if the operations encounter unexpected errors.
When using the Go driver, you can create a new session from a
Client
instance as a Session
type. We recommend that you reuse
your client for multiple sessions and transactions instead of
instantiating a new client each time.
Warning
Use a Session
only with the Client
(or associated
Database
or Collection
) that created it. Using a
Session
with a different Client
results in operation
errors.
Warning
Implementations of Session
are not safe for concurrent use by multiple goroutines.
Session Methods
After you start a session by using the StartSession()
method on your
client, you can modify the session state by using the method set
provided by the returned Session
. The following table describes
these methods:
Method | Description |
---|---|
StartTransaction() | Starts a new transaction, configured with the given options, on
this session. Returns an error if there is already
a transaction in progress for the session. To learn more about
this method, see the startTransaction() page in the Server manual. Parameter: TransactionOptions Return Type: error |
AbortTransaction() | Ends the active transaction for this session. Returns an
error if there is no active transaction for the session or the
transaction has been committed or ended. To learn more about
this method, see the abortTransaction() page in the Server manual. Parameter: Context Return Type: error |
CommitTransaction() | Commits the active transaction for this session. Returns an
error if there is no active transaction for the session or if the
transaction was ended. To learn more about
this method, see the commitTransaction() page in the Server manual. The CommitTransaction() method is an idempotent function, which
means that you can attempt to commit a transaction multiple times without changing data after the first successful commit.
A transaction can succeed but return an error with the
UnknownTransactionCommitResult label. If you rerun the
CommitTransaction() method after receiving this error,
your data is not changed by the repeat attempts.Parameter: Context Return Type: error |
WithTransaction() | Starts a transaction on this session and runs the fn
callback.Parameters: Context , fn func(ctx SessionContext) , TransactionOptions Return Type: interface{} , error |
EndSession() | Ends any existing transactions and closes the session. Parameter: Context Return Type: none |
A Session
also has methods to retrieve session
properties and modify mutable session properties. View the API
documentation to learn more about these methods.
Session and Transaction Options
You can set options at the session level and the transaction level to
customize how the driver performs a transaction. The following steps
describe how to set options for all transactions run within a given
Session
:
Create a
TransactionOptions
instance. You can specify options such as a write concern, read concern, and read preference for all transactions run in a given session.Create a
SessionOptions
instance by calling theSetDefaultTransactionOptions()
method, passing theTransactionOptions
instance as the parameter.You can also specify other session options such as causal consistency in your
SessionOptions
instance.Pass the
SessionOptions
instance to theclient.StartSession()
method.
The following code specifies session and transaction options, then creates a session with these options:
txnOpts := options.Transaction().SetReadConcern(readconcern.Majority()) sessOpts := options.Session().SetDefaultTransactionOptions(txnOpts) session, err := client.StartSession(sessOpts) if err != nil { return err }
Example
The following example shows how you can create a session, create a transaction, and commit a multi-document insert operation through the following steps:
Create a session from the client using the
StartSession()
method.Use the
WithTransaction()
method to start a transaction.Insert multiple documents. The
WithTransaction()
method executes the insert and commits the transaction. If any operation results in errors,WithTransaction()
handles canceling the transaction.Close the transaction and session using the
EndSession()
method.
wc := writeconcern.Majority() txnOptions := options.Transaction().SetWriteConcern(wc) // Starts a session on the client session, err := client.StartSession() if err != nil { panic(err) } // Defers ending the session after the transaction is committed or ended defer session.EndSession(context.TODO()) // Inserts multiple documents into a collection within a transaction, // then commits or ends the transaction result, err := session.WithTransaction(context.TODO(), func(ctx context.Context) (interface{}, error) { result, err := coll.InsertMany(ctx, []interface{}{ bson.D{{"title", "The Bluest Eye"}, {"author", "Toni Morrison"}}, bson.D{{"title", "Sula"}, {"author", "Toni Morrison"}}, bson.D{{"title", "Song of Solomon"}, {"author", "Toni Morrison"}}, }) return result, err }, txnOptions)
If you require more control over your transactions, you can find an example showing how to manually create, commit, and end transactions in the full code example.
Additional Information
For more information about insert operations, see the Insert a Document fundamentals page.
For more information about specifying write concerns in the Go driver, see Write Concern.
For an additional example using sessions and transactions with the Go driver, see the developer blog post on Multi-Document ACID Transactions.
API Documentation
To learn more about any of the types or methods discussed in this guide, see the following API Documentation: