Uploaded image for project: 'Drivers'
  1. Drivers
  2. DRIVERS-655

Provide transaction example using new withTransaction API

    XMLWordPrintableJSON

Details

    • Icon: Task Task
    • Resolution: Done
    • Icon: Major - P3 Major - P3
    • None
    • None
    • None
    • $i18n.getText("admin.common.words.hide")
      Key Status/Resolution FixVersion
      NODE-2141 Fixed 3.3.3
      JAVA-3413 Done
      SCALA-558 Won't Do
      PYTHON-1972 Fixed 3.10
      PHPLIB-474 Fixed 1.5.0
      CXX-1811 Fixed 3.5.0
      MOTOR-370 Fixed 2.1
      CSHARP-2720 Fixed 2.10.0
      GODRIVER-1259 Fixed 1.4.0
      RUBY-1908 Fixed 2.13.0.beta1
      CDRIVER-3347 Fixed 1.16.0
      PHPLIB-548 Duplicate
      RUST-387 Fixed 2.5.0
      SWIFT-814 Won't Do
      $i18n.getText("admin.common.words.show")
      #scriptField, #scriptField *{ border: 1px solid black; } #scriptField{ border-collapse: collapse; } #scriptField td { text-align: center; /* Center-align text in table cells */ } #scriptField td.key { text-align: left; /* Left-align text in the Key column */ } #scriptField a { text-decoration: none; /* Remove underlines from links */ border: none; /* Remove border from links */ } /* Add green background color to cells with FixVersion */ #scriptField td.hasFixVersion { background-color: #00FF00; /* Green color code */ } /* Center-align the first row headers */ #scriptField th { text-align: center; } Key Status/Resolution FixVersion NODE-2141 Fixed 3.3.3 JAVA-3413 Done SCALA-558 Won't Do PYTHON-1972 Fixed 3.10 PHPLIB-474 Fixed 1.5.0 CXX-1811 Fixed 3.5.0 MOTOR-370 Fixed 2.1 CSHARP-2720 Fixed 2.10.0 GODRIVER-1259 Fixed 1.4.0 RUBY-1908 Fixed 2.13.0.beta1 CDRIVER-3347 Fixed 1.16.0 PHPLIB-548 Duplicate RUST-387 Fixed 2.5.0 SWIFT-814 Won't Do

    Description

      *update:* Removed the admin database from connection string in comment.

      Could we get withTxn API example where we basically insert documents into two collections?(FYI – we'll keep the old API examples as well so as not to strand people)

      The example should the comments Start Transactions withTxn API Example 1 and End Transactions withTxn API Example 1 as delimiters. If we could include the comments throughout the main steps as shown below:

      For example, the template in python:

      # Start Transactions withTxn API Example 1
       
      # For a replica set, include the replica set name and a seedlist of the members in the URI string; e.g.
      # uriString = 'mongodb://mongodb0.example.com:27017,mongodb1.example.com:27017/?replicaSet=myRepl'
      # For a sharded cluster, connect to the mongos instances; e.g.
      # uriString = 'mongodb://mongos0.example.com:27017,mongos1.example.com:27017/'
       
      client = MongoClient(uriString)
       
      my_write_concern_majority = WriteConcern('majority', wtimeout=1000)
       
      # Prereq: Create collections. CRUD operations in transactions must be on existing collections.
       
      client.get_database(
          'mydb1',
          write_concern=my_write_concern_majority).foo.insert_one({'abc': 0})
      client.get_database(
          'mydb2',
          write_concern=my_write_concern_majority).bar.insert_one({'xyz': 0})
       
      # Step 1: Define the callback that specifies the sequence of operations to perform inside the transactions.
       
      def callback(my_session):
          collection_one = my_session.client.mydb1.foo
          collection_two = my_session.client.mydb2.bar
       
          # Important:: You must pass the session to the operations.
       
          collection_one.insert_one({'abc': 1}, session=my_session)
          collection_two.insert_one({'xyz': 999}, session=my_session)
       
      #. Step 2: Start a client session.
       
      with client.start_session() as session:
       
          # Step 3: Use with_transaction to start a transaction, execute the callback, and commit (or abort on error).
       
          session.with_transaction(callback,
                                   read_concern=ReadConcern('local'),
                                   write_concern=my_write_concern_majority,
                                   read_preference=ReadPreference.PRIMARY)
       
       
      # End Transactions withTxn API Example 1
      

      For example, in JAVA:

      /* Start Transactions withTxn API Example 1 */
      /*
        For a replica set, include the replica set name and a seedlist of the members in the URI string; e.g.
        String uri = "mongodb://mongodb0.example.com:27017,mongodb1.example.com:27017/?replicaSet=myRepl";
        For a sharded cluster, connect to the mongos instances; e.g.
        String uri = "mongodb://mongos0.example.com:27017,mongos1.example.com:27017/";
       */
       
      final MongoClient client = MongoClients.create(uri);
       
      /*
          Prereq: Create collections. CRUD operations in transactions must be on existing collections.
       */
       
      client.getDatabase("mydb1").getCollection("foo")
              .withWriteConcern(WriteConcern.MAJORITY).insertOne(new Document("abc", 0));
      client.getDatabase("mydb2").getCollection("bar")
              .withWriteConcern(WriteConcern.MAJORITY).insertOne(new Document("xyz", 0));
       
      /* Step 1: Start a client session. */
       
      final ClientSession clientSession = client.startSession();
       
      /* Step 2: Optional. Define options to use for the transaction. */
       
      TransactionOptions txnOptions = TransactionOptions.builder()
              .readPreference(ReadPreference.primary())
              .readConcern(ReadConcern.LOCAL)
              .writeConcern(WriteConcern.MAJORITY)
              .build();
       
      /* Step 3: Define the sequence of operations to perform inside the transactions. */
       
      TransactionBody txnBody = new TransactionBody<String>() {
          public String execute() {
              MongoCollection<Document> coll1 = client.getDatabase("mydb1").getCollection("foo");
              MongoCollection<Document> coll2 = client.getDatabase("mydb2").getCollection("bar");
       
              /*
                 Important:: You must pass the session to the operations.
               */
              coll1.insertOne(clientSession, new Document("abc", 1));
              coll2.insertOne(clientSession, new Document("xyz", 999));
              return "Inserted into collections in different databases";
          }
      };
      try {
          /*
             Step 4: Use .withTransaction() to start a transaction,
             execute the callback, and commit (or abort on error).
          */
       
          clientSession.withTransaction(txnBody, txnOptions);
      } catch (RuntimeException e) {
          // some error handling
      } finally {
          clientSession.close();
      }
       
      /* End Transactions withTxn API Example 1 */
      

      As always, please modify as appropriate for good programming practices in your specific driver.

      Attachments

        Activity

          People

            Unassigned Unassigned
            kay.kim@mongodb.com Kay Kim (Inactive)
            Votes:
            1 Vote for this issue
            Watchers:
            5 Start watching this issue

            Dates

              Created:
              Updated:
              Resolved: