Skip to content

Commit 9256dff

Browse files
authored
DOCSP-13849: transactions page (#166)
* DOCSP-13849-sessions-pg * first pass fixes * change page to focus on transactions * small fixes * MD tech review comments * MD comments 2 and small fixes * changed code and small fixes * MW PR fixes 1 * wording fix
1 parent bc4cdc0 commit 9256dff

File tree

3 files changed

+243
-0
lines changed

3 files changed

+243
-0
lines changed

source/fundamentals.txt

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -16,6 +16,7 @@ Fundamentals
1616
/fundamentals/crud
1717
/fundamentals/aggregation
1818
/fundamentals/indexes
19+
/fundamentals/transactions
1920
/fundamentals/collations
2021
/fundamentals/gridfs
2122
/fundamentals/time-series
Lines changed: 158 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,158 @@
1+
.. _golang-transactions:
2+
3+
============
4+
Transactions
5+
============
6+
7+
.. default-domain:: mongodb
8+
9+
.. contents:: On this page
10+
:local:
11+
:backlinks: none
12+
:depth: 2
13+
:class: singlecol
14+
15+
Overview
16+
--------
17+
18+
In this guide, you can learn how to use **transactions** with the
19+
{+driver-long+}. :manual:`Transactions </core/transactions/>` allow you
20+
to run a series of operations that do not change any data until the
21+
transaction is committed. If any operation in the transaction fails, the
22+
driver aborts the transaction and discards all data changes before they
23+
ever become visible.
24+
25+
In MongoDB, transactions run within logical **sessions**. A
26+
:manual:`session </reference/server-sessions/>` is a
27+
grouping of related read or write operations that you intend to run
28+
sequentially. Sessions enable :manual:`causal consistency </core/read-isolation-consistency-recency/#causal-consistency>`
29+
for a group of operations or allow you to execute operations in an :website:`ACID
30+
transaction </basics/acid-transactions>`. MongoDB guarantees that the data
31+
involved in your transaction operations remains , even if the operations
32+
encounter unexpected errors.
33+
34+
With the {+driver-short+}, you can create a new session from a
35+
``Client`` instance as a ``Session`` type.
36+
37+
.. warning::
38+
39+
You should use a ``Session`` only with the ``Client`` (or associated
40+
``Database`` or ``Collection``) that created it. Using a
41+
``Session`` with a different ``Client`` will result in operation
42+
errors.
43+
44+
.. warning::
45+
46+
Implementations of ``Session`` are not safe for concurrent use by multiple `goroutines
47+
<https://www.golang-book.com/books/intro/10>`__.
48+
49+
Methods
50+
-------
51+
52+
After you start a session using the ``StartSession()`` method, you can modify
53+
the session state using the method set provided by the ``Session`` interface. The
54+
following table describes these methods:
55+
56+
.. list-table::
57+
:widths: 25 75
58+
:header-rows: 1
59+
60+
* - Method
61+
- Description
62+
63+
* - ``StartTransaction()``
64+
- | Starts a new transaction, configured with the given options, on
65+
this session. Returns an error if there is already
66+
a transaction in progress for the session. For more
67+
information, see the :manual:`manual entry </reference/method/Session.startTransaction/>`.
68+
|
69+
| **Parameter**: ``TransactionOptions``
70+
| **Return Type**: ``error``
71+
72+
* - ``AbortTransaction()``
73+
- | Aborts the active transaction for this session. Returns an
74+
error if there is no active transaction for the session or the
75+
transaction has been committed or aborted. For more
76+
information, see the :manual:`manual entry </reference/method/Session.abortTransaction/>`.
77+
|
78+
| **Parameter**: ``Context``
79+
| **Return Type**: ``error``
80+
81+
* - ``CommitTransaction()``
82+
- | Commits the active transaction for this session. Returns an
83+
error if there is no active transaction for the session or the
84+
transaction has been aborted. For more
85+
information, see the :manual:`manual entry </reference/method/Session.commitTransaction/>`.
86+
|
87+
| **Parameter**: ``Context``
88+
| **Return Type**: ``error``
89+
90+
* - ``WithTransaction()``
91+
- | Starts a transaction on this session and runs the ``fn``
92+
callback.
93+
|
94+
| **Parameters**: ``Context``, ``fn func(ctx SessionContext)``, ``TransactionOptions``
95+
| **Return Type**: ``interface{}``, ``error``
96+
97+
* - ``EndSession()``
98+
- | Aborts any existing transactions and closes the session.
99+
|
100+
| **Parameter**: ``Context``
101+
| **Return Type**: none
102+
103+
The ``Session`` interface also has methods to retrieve session
104+
properties and modify mutable session properties. Find more information
105+
in the :ref:`API documentation <api-docs-transaction>`.
106+
107+
Example
108+
-------
109+
110+
The following example shows how you can create a session, create a
111+
transaction, and commit a multi-document insert operation through the
112+
following steps:
113+
114+
1. Create a session from the client using the ``StartSession()`` method.
115+
#. Use the ``WithTransaction()`` method to start a transaction.
116+
#. Insert multiple documents. The ``WithTransaction()`` method executes the
117+
insert and commits the transaction. If any operation results in
118+
errors, ``WithTransaction()`` handles aborting the transaction.
119+
#. Close the transaction and session using the ``EndSession()`` method.
120+
121+
.. literalinclude:: /includes/fundamentals/code-snippets/transaction.go
122+
:language: go
123+
:dedent:
124+
:emphasize-lines: 4,8,10-11
125+
:start-after: start-session
126+
:end-before: end-session
127+
128+
If you need more control over your transactions, you can find an example
129+
showing how to manually create, commit, and abort transactions in the
130+
`full code example <https://raw.githubusercontent.com/mongodb/docs-golang/{+docs-branch+}/source/includes/fundamentals/code-snippets/transaction.go>`__.
131+
132+
Additional Information
133+
----------------------
134+
135+
For more information about insert operations, see the
136+
:ref:`golang-insert-guide` fundamentals page.
137+
138+
For more information about write concerns, see the
139+
:ref:`golang-write-read-pref` fundamentals page.
140+
141+
For an additional example using sessions and transactions with the {+driver-short+}, see the
142+
:website:`developer blog post on Multi-Document ACID Transactions
143+
</developer/languages/go/golang-multi-document-acid-transactions/>`.
144+
145+
.. _api-docs-transaction:
146+
147+
API Documentation
148+
~~~~~~~~~~~~~~~~~
149+
150+
To learn more about any of the types or methods discussed in this
151+
guide, see the following API Documentation:
152+
153+
- `Session <{+api+}/mongo#Session>`__
154+
- `Client <{+api+}/mongo#Client>`__
155+
- `StartSession() <{+api+}/mongo#Client.StartSession>`__
156+
- `TransactionOptions <{+api+}/mongo/options#TransactionOptions>`__
157+
- `SetWriteConcern() <{+api+}/mongo/options#TransactionOptions.SetWriteConcern>`__
158+
- `InsertMany() <{+api+}/mongo#Collection.InsertMany>`__
Lines changed: 84 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,84 @@
1+
package main
2+
3+
import (
4+
"context"
5+
"fmt"
6+
"log"
7+
"os"
8+
9+
"go.mongodb.org/mongo-driver/bson"
10+
"go.mongodb.org/mongo-driver/mongo"
11+
"go.mongodb.org/mongo-driver/mongo/options"
12+
"go.mongodb.org/mongo-driver/mongo/writeconcern"
13+
)
14+
15+
func main() {
16+
17+
var uri string
18+
if uri = os.Getenv("MONGODB_URI"); uri == "" {
19+
log.Fatal("You must set your 'MONGODB_URI' environmental variable. See\n\t https://www.mongodb.com/docs/drivers/go/current/usage-examples/")
20+
}
21+
22+
client, err := mongo.Connect(context.Background(), options.Client().ApplyURI(uri))
23+
if err != nil {
24+
panic(err)
25+
}
26+
defer client.Disconnect(context.TODO())
27+
28+
database := client.Database("myDB")
29+
coll := database.Collection("myColl")
30+
31+
// start-session
32+
wc := writeconcern.New(writeconcern.WMajority())
33+
txnOptions := options.Transaction().SetWriteConcern(wc)
34+
35+
session, err := client.StartSession()
36+
if err != nil {
37+
panic(err)
38+
}
39+
defer session.EndSession(context.TODO())
40+
41+
result, err := session.WithTransaction(context.TODO(), func(ctx mongo.SessionContext) (interface{}, error) {
42+
result, err := coll.InsertMany(ctx, []interface{}{
43+
bson.D{{"title", "The Bluest Eye"}, {"author", "Toni Morrison"}},
44+
bson.D{{"title", "Sula"}, {"author", "Toni Morrison"}},
45+
bson.D{{"title", "Song of Solomon"}, {"author", "Toni Morrison"}},
46+
})
47+
return result, err
48+
}, txnOptions)
49+
// end-session
50+
51+
fmt.Printf("Inserted _id values: %v\n", result)
52+
53+
// MANUAL TRANSACTION EXAMPLE
54+
// uncomment this section to run this code
55+
56+
// err = mongo.WithSession(context.TODO(), session, func(ctx mongo.SessionContext) error {
57+
// if err = session.StartTransaction(txnOptions); err != nil {
58+
// return err
59+
// }
60+
61+
// docs := []interface{}{
62+
// bson.D{{"title", "The Year of Magical Thinking"}, {"author", "Joan Didion"}},
63+
// bson.D{{"title", "Play It As It Lays"}, {"author", "Joan Didion"}},
64+
// bson.D{{"title", "The White Album"}, {"author", "Joan Didion"}},
65+
// }
66+
// result, err := coll.InsertMany(ctx, docs)
67+
// if err != nil {
68+
// return err
69+
// }
70+
71+
// if err = session.CommitTransaction(ctx); err != nil {
72+
// return err
73+
// }
74+
75+
// fmt.Println(result.InsertedIDs)
76+
// return nil
77+
// })
78+
// if err != nil {
79+
// if err := session.AbortTransaction(context.TODO()); err != nil {
80+
// panic(err)
81+
// }
82+
// panic(err)
83+
// }
84+
}

0 commit comments

Comments
 (0)