Transaction Management

Transactions

A transaction is a unit of work that is performed against a database. Transactions are units or sequences of work accomplished in a logical order, if one fail the code should have the possibility to roll-back so either all is executed or none. In MongoDB, operations on single documents are atomic. Because you can use embedded documents and arrays to capture relationships between data in a single document structure instead of normalizing across multiple documents and collections, this single-document atomicity obviates the need for multi-document transactions for many practical use cases.

Since MongoDB 4.0, MongoDB supports multi-document transactions. With distributed transactions, transactions can be used across multiple operations, collections, databases, documents, and shards.

How to create transactions in MongoDB

Staring a session

A session is just a group of queries that are grouped together.

session = db.getMongo().startSession();
session.startTransaction();

Creating transations

To create a transaction inside a session, we use the session variable using the name of our database, collection and finally the query.

//transation 1
session.getDatabase("db").coll.delete({"_id" : "yamicode});
//transaction 2
session.getDatabase("db").coll2.delete({"_id" : "yamicode});

Running transations

To commit and run our transation we use the commitTransaction method.

session.commitTransaction()
session.endSession()

Abort transations

session.abortTransaction()