 Photo by [Madison Grooms](https://unsplash.com/@zeldygirl?utm_source=medium&utm_medium=referral) on [Unsplash](https://unsplash.com?utm_source=medium&utm_medium=referral) > _Support for transactions in MongoDB has been something long desired by many. With MongoDB v4.0, the wait is now over. Welcome to multi-document transactions for replica sets._ In a [MongoDB](https://hackernoon.com/tagged/mongodb) [database](https://hackernoon.com/tagged/database) application when you have parent-child relationship between two entities, such as _orders & order details_, you typically embed the child documents (_order details_) in a parent document (_order_). Such schema design way will not only help with faster reads, but also help meet the atomicity. A write operations on a single document is atomic. However, _‘How do you maintain the atomicity while working with multiple documents?’_ This is one of the many articles in multi-part series, [Mastering MongoDB — One tip a day](https://medium.com/p/mastering-mongodb-5544e16df023), solely created for you to master [MongoDB](https://www.mongodb.com) by learning _‘one tip a day’_. In a few series of articles, I would like to give various tips to help you answer the above question. This article discusses _multi-document transactions_, a new feature in MongoDB v4.0 — its applications, use case scenarios and finally some hands-on lab exercises. ### Mastering — Multi-document transactions ### What are Transactions In MongoDB, a write operations on a single document is [atomic](https://docs.mongodb.com/manual/core/write-operations-atomicity/), even if the operation modifies multiple embedded documents within a single document. When a single write operation, like [updateMany](https://docs.mongodb.com/manual/reference/method/db.collection.updateMany/), modifies multiple documents, the modification of each document is atomic, but the operation as a whole is not atomic. Some of the use cases may also require you to modify multiple write operations as part of single operation. In such scenarios you do need _transactions_ to enforce atomicity across multiple write operations. ### Why use Transactions Until MongoDB v4.0 the only way you could emulate _transactions_ is by implementing a [two-phase commit](https://docs.mongodb.com/manual/tutorial/perform-two-phase-commits/) in your application. [Emmanuel Olaojo](https://medium.com/@emmanuelolaojo) wrote an article, [“Fawn: _transactions_ in MongoDB”](https://codeburst.io/fawn-transactions-in-mongodb-988d8646e564), on two-phase commits using [Fawn](https://www.npmjs.com/package/fawn) module for [Node.js](https://nodejs.org/) applications. Please be aware that the two-phase commits can only offer transaction-like semantics. While using two-phase commit, it is possible for applications to return intermediate data during the two-phase commit or rollback. The MongoDB v4.0 introduces _multi-document transactions_ for replica sets and can be used across multiple operations, collections, and documents. The multi-document _transactions_ provide a globally consistent view of data, and enforce all-or-nothing execution to maintain data integrity. The _transactions_ will have following properties * When a transaction is committed, all data changes made in the transaction are saved. * If any operation in the transaction fails, the transaction aborts * When a transaction aborts/aborted, all data changes made in the transaction are discarded. * Until a transaction is committed, no write operations in the transaction are visible outside the transaction. ### Hands-On lab exercises This lab exercise helps you understand how to make use of _transactions_ within a MongoDB shell. Since the Multi-document _transactions_ are available only for replica sets, please ensure that you do have at least 1 member replicaset rather than standalone _mongod_. Before we get started, I want you to be aware of a few points * You can only specify read/write (CRUD) operations on existing collections. * A multi-document transaction cannot include an insert operation that would result in the creation of a new collection. * Transactions are associated with a session. * At any given time, you can have at most one open transaction for a session. * To associate read and write operations with an open transaction, you pass the session to the operations. #### Setup environment First, you would need an environment to play around. If you already have a MongoDB v4.0 replicaset environment, you may skip this step.  A bash script with download MongoDB v4.0 release candidate and create a 1 member replica set The next set of exercises will illustrate how the commitTransaction / abortTransaction work and most importantly also covers how multiple write operations with _write conflicts_ lead to _abortTransaction_. To help you understand better I have included the output of these commands right below them as comments. #### Saving data changes with commitTransaction The below MongoDB shell commands shows a _person_ collection with some sample data in it. Notice that the newly added document in the _transaction_ is not visible on the _db.person_ collection object until the _session1_ is committed.  MongoDB commands illustrating the data changes in transaction are save when the transaction is committed. #### Discarding data changes with abortTransaction The below MongoDB shell commands shows a _person_ collection with some sample data in it. Notice that the newly added document in the _transaction_ is not visible on the _db.person_ collection object until the _session1_ is aborted.  MongoDB commands illustrating the data changes in transaction are discarded when the transaction is aborted on the session. #### Transactions with no write conflicts can be committed In the below code, you may notice that there are multiple write operations (_insert_, _update_ and _delete_) are invoked from multiple scopes, inside/outside of transaction. As long as there is no _WriteConflict_, you can successfully commit these transaction.  MongoDB commands illustrating transactions with no write conflicts can successfully commit #### Transactions with write conflicts are aborted If two or more write operations modify the same document from different scopes, then the data changes in one transaction impact the data changes from the other transactions. When such _WriteConflict_ exists, the operations would result in _TransientTransactionError_ and _abortTransaction_. These writes could be any combination of insert/update/delete operations. Below example shows two delete operations on same document invoked in two different transactions.  MongoDB commands illustrating multiple transactions with write conflicts are aborted ### Summary The support for the Multi-document _transactions_ for replica sets is just the beginning. The future release may address the _transactions_ across the sharded deployment and various isolation levels that you may have exposure from other relational databases. I want to remind an important point — > “Just because you now have support for transactions, you must not design the data model around 3rd normal form. You must always have an effective MongoDB schema design to ensure your application is highly performant. Multi-document transaction incurs a greater performance cost when compared to single document writes. So, “What is the performance cost of using transactions?”. Great question! But that’s a topic for another day. Hopefully, you learned something new today on you scale the path to “[Mastering MongoDB — One tip a day](https://medium.com/p/mastering-mongodb-5544e16df023)”.