Transactions
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
You should 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.
Methods
After you start a session by using the StartSession()
method, you can modify
the session state by using the method set provided by the Session
interface. 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. NoteRetrying a TransactionThe A transaction can succeed but return an error with the
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 |
The Session
interface also has methods to retrieve session
properties and modify mutable session properties. Find more information
in the API documentation.
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 aborting the transaction.Close the transaction and session using the
EndSession()
method.
wc := writeconcern.New(writeconcern.WMajority()) txnOptions := options.Transaction().SetWriteConcern(wc) session, err := client.StartSession() if err != nil { panic(err) } defer session.EndSession(context.TODO()) result, err := session.WithTransaction(context.TODO(), func(ctx mongo.SessionContext) (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 write concerns, see the Modify Execution of CRUD Operations fundamentals page.
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: