@@ -11,6 +11,7 @@ package documentation_examples
11
11
12
12
import (
13
13
"context"
14
+ "fmt"
14
15
"io/ioutil"
15
16
logger "log"
16
17
"sync/atomic"
@@ -1937,6 +1938,60 @@ func TransactionsExamples(ctx context.Context, client *mongo.Client) error {
1937
1938
1938
1939
// End Transactions Retry Example 3
1939
1940
1941
+ // Start Transactions withTxn API Example 1
1942
+
1943
+ // WithTransactionExample is an example of using the Session.WithTransaction function.
1944
+ func WithTransactionExample () {
1945
+ ctx := context .Background ()
1946
+ // For a replica set, include the replica set name and a seedlist of the members in the URI string; e.g.
1947
+ // uri := "mongodb://mongodb0.example.com:27017,mongodb1.example.com:27017/?replicaSet=myRepl"
1948
+ // For a sharded cluster, connect to the mongos instances; e.g.
1949
+ // uri := "mongodb://mongos0.example.com:27017,mongos1.example.com:27017/"
1950
+ var uri string
1951
+
1952
+ clientOpts := options .Client ().ApplyURI (uri )
1953
+ client , err := mongo .Connect (ctx , clientOpts )
1954
+ if err != nil {
1955
+ panic (err )
1956
+ }
1957
+ defer func () { _ = client .Disconnect (ctx ) }()
1958
+
1959
+ // Prereq: Create collections.
1960
+ wcMajority := writeconcern .New (writeconcern .WMajority (), writeconcern .WTimeout (1 * time .Second ))
1961
+ wcMajorityCollectionOpts := options .Collection ().SetWriteConcern (wcMajority )
1962
+ fooColl := client .Database ("mydb1" ).Collection ("foo" , wcMajorityCollectionOpts )
1963
+ barColl := client .Database ("mydb1" ).Collection ("bar" , wcMajorityCollectionOpts )
1964
+
1965
+ // Step 1: Define the callback that specifies the sequence of operations to perform inside the transaction.
1966
+ callback := func (sessCtx mongo.SessionContext ) (interface {}, error ) {
1967
+ // Important: You must pass sessCtx as the Context parameter to the operations for them to be executed in the
1968
+ // transaction.
1969
+ if _ , err := fooColl .InsertOne (sessCtx , bson.D {{"abc" , 1 }}); err != nil {
1970
+ return nil , err
1971
+ }
1972
+ if _ , err := barColl .InsertOne (sessCtx , bson.D {{"xyz" , 999 }}); err != nil {
1973
+ return nil , err
1974
+ }
1975
+
1976
+ return nil , nil
1977
+ }
1978
+
1979
+ // Step 2: Start a session and run the callback using WithTransaction.
1980
+ session , err := client .StartSession ()
1981
+ if err != nil {
1982
+ panic (err )
1983
+ }
1984
+ defer session .EndSession (ctx )
1985
+
1986
+ result , err := session .WithTransaction (ctx , callback )
1987
+ if err != nil {
1988
+ panic (err )
1989
+ }
1990
+ fmt .Printf ("result: %v\n " , result )
1991
+ }
1992
+
1993
+ // End Transactions withTxn API Example 1
1994
+
1940
1995
// ChangeStreamExamples contains examples of changestream operations.
1941
1996
func ChangeStreamExamples (t * testing.T , db * mongo.Database ) {
1942
1997
ctx := context .Background ()
0 commit comments