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

Provide transaction example using new withTransaction API

    XMLWordPrintable

Details

    • Task
    • Status: Implementing
    • Major - P3
    • Resolution: Unresolved
    • None
    • None

    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

        Issue Links

          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: