// 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
|