Uploaded image for project: 'C Driver'
  1. C Driver
  2. CDRIVER-2663

Provide Transactions example for Docs

    • Type: Icon: Improvement Improvement
    • Resolution: Fixed
    • Priority: Icon: Major - P3 Major - P3
    • 1.11.0, 1.12.0
    • Affects Version/s: None
    • Component/s: docs, libmongoc
    • Labels:
      None

      Hi –
      for the manual – would like to pop in driver examples in
      https://docs.mongodb.com/master/core/transactions/#transactions-and-mongodb-drivers

      We'll have the following example for the mongo shell. If we could get the corresponding driver example

      Note: I've modified in the manual for the shell examples to have the transaction happen in a function updateEmployeeInfo(session) so as not to have that horrible txnAborted flag around – but whatever is good practice for the language of your choice. Let me know if I should update the example here to reflect that.

      // Start Transaction Example 1
      txnAborted = false;
      
      // Start a session.
      session = db.getMongo().startSession( { mode: "primary" });
      
      employeesCollection = session.getDatabase("hr").employees;
      eventsCollection = session.getDatabase("reporting").events;
      
      // Start a transaction for the session that uses:
      // - read concern "snapshot"
      // - write concern "majority"
      session.startTransaction( {
         readConcern: { level: "snapshot" },
         writeConcern: { w: "majority" }
      } );
      
      try{
      
         employeesCollection.updateOne( { employee: 3 }, { $set: { status: "Inactive" } } );
         eventsCollection.insertOne( { employee: 3, status: { new: "Inactive", old: "Active" } } );
      
      } catch (error) {
         txnAborted = true;
         print ("Abort transaction.");
         session.abortTransaction();  // Uses write concern "majority"
      }
      
      // Until commit, no data changes from the two operations in the transaction are visible outside the transaction
      
      if (!txnAborted) {
         print ("Commit transaction.");
         session.commitTransaction(); // Uses write concern "majority"
      }
      
      session.endSession();
      
      // End Transaction Example 1
      

      cc: rathi.gnanasekaran scott.lhommedieu behackett

            Assignee:
            jesse@mongodb.com A. Jesse Jiryu Davis
            Reporter:
            rathi.gnanasekaran Rathi Gnanasekaran
            Votes:
            0 Vote for this issue
            Watchers:
            3 Start watching this issue

              Created:
              Updated:
              Resolved: