Transactions
Overview
In this guide, you can learn how to use transactions with the MongoDB Go Driver. 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 fails, the driver aborts 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 , even if the operations encounter unexpected errors.
With the Go driver, you can create a new session from a
Client
instance as a Session
type.
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
will result in operation
errors.
Warning
Implementations of Session
are not safe for concurrent use by multiple goroutines.
Methods
After you start a session using the StartSession()
method, you can modify
the session state 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. For more
information, see the manual entry. Parameter: TransactionOptions Return Type: error |
AbortTransaction() | Aborts 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 aborted. For more
information, see the manual entry. 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 the
transaction has been aborted. For more
information, see the manual entry. 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() | Aborts 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 need more control over your transactions, you can find an example showing how to manually create, commit, and abort 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: