Skip to content

Instantly share code, notes, and snippets.

@j-chimienti
Last active July 7, 2019 18:08
Show Gist options
  • Select an option

  • Save j-chimienti/8161d9adbf21ee6e59f1024909161097 to your computer and use it in GitHub Desktop.

Select an option

Save j-chimienti/8161d9adbf21ee6e59f1024909161097 to your computer and use it in GitHub Desktop.
// Start a session.
session = db.getMongo().startSession( { readPreference: { mode: "primary" } } );
// session = db.getMongo().startSession()
employeesCollection = session.getDatabase("hr").employees;
eventsCollection = session.getDatabase("reporting").events;
// Start a transaction
session.startTransaction( { readConcern: { level: "snapshot" }, writeConcern: { w: "majority" } } );
// session.startTransaction()
// Operations inside the transaction
try {
employeesCollection.updateOne( { employee: 3 }, { $set: { status: "Inactive" } } );
eventsCollection.insertOne( { employee: 3, status: { new: "Inactive", old: "Active" } } );
} catch (error) {
// Abort transaction on error
session.abortTransaction();
throw error;
}
// Commit the transaction using write concern set at transaction start
session.commitTransaction();
session.endSession();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment