[DRIVERS-655] Provide transaction example using new withTransaction API Created: 28/May/19  Updated: 14/Apr/23  Resolved: 14/Apr/23

Status: Closed
Project: Drivers
Component/s: None
Fix Version/s: None

Type: Task Priority: Major - P3
Reporter: Kay Kim (Inactive) Assignee: Unassigned
Resolution: Done Votes: 1
Labels: None
Remaining Estimate: Not Specified
Time Spent: Not Specified
Original Estimate: Not Specified

Issue Links:
Depends
depends on CDRIVER-3347 Provide transaction example using new... Closed
depends on CSHARP-2720 Provide transaction example using new... Closed
depends on CXX-1811 Provide transaction example using new... Closed
depends on GODRIVER-1259 Provide transaction example using new... Closed
depends on JAVA-3413 Provide transaction example using new... Closed
depends on MOTOR-370 Provide transaction example using new... Closed
depends on NODE-2141 Provide transaction example using new... Closed
depends on PHPLIB-474 Provide transaction example using new... Closed
depends on PYTHON-1972 Provide transaction example using new... Closed
depends on PHPLIB-548 Provide transaction example using new... Closed
depends on RUBY-1908 Provide transaction example using new... Closed
depends on RUST-387 Provide transaction example using new... Closed
Related
related to DRIVERS-2606 Simplify transaction options in conve... Implementing
Driver Compliance:
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.


Generated at Thu Feb 08 08:22:03 UTC 2024 using Jira 9.7.1#970001-sha1:2222b88b221c4928ef0de3161136cc90c8356a66.