MongoDB 4.0 Release Candidate is available, which add supports for multi-document transactions, will work across a single replica set, and MongoDB 4.2* will support transactions across a sharded deployment.

The most awaiting feature scheduled for release this summer, will open the door to lots of excitement in the community enabling tons of enhancement that can be made to existing and future projects using MongoDB.

Multi-document transactions will enables developers to focus on writting mission critical application, instead of writting complex logic at application layer to ensure consistency.

While atomicity at single level document is already supported by MongoDB, which solves most of the cases in application development, only 10-20% of the cases requires the use of multi-document transactions.

Multi-document transactions being supported by MongoDB doesn't means, that Developers/DBAs should start normalizing there schema - as they would used to do in RDBMS, as that would add extra overhead on the Mongod.

For most of the senarios modeling your data as denormalized data model (embedded documents and arrays) will minimize the need for multi-document transactions.

Limitiations of Multi-document transactions

  • This features are available for the WiredTiger storage engine and in-memory storage engines only.
  • Doesn't works with config, admin, or local databases.
  • Query plan is not available.
  • The individual write operations inside the transaction are not retryable, regardless of whether retryWrites is set to true.

Things to remember when multi-document transaction is enabled

  • If you are running with access control, you must have privileges for the operations in the transaction.
  • By default, transactions waits 5 milliseconds to acquire locks required by the operations in the transaction. If the transaction cannot acquire its required locks within the 5 milliseconds, the transaction aborts.
  • If a session ends and it has an open transaction, the transaction aborts, you are also required to pass the session to each operations, when using drivers.

Below is the sample python code using transaction

with client.start_session() as s:
    s.start_transaction()
    try:
        collection.insert_one(doc1, session=s)
        collection.insert_one(doc2, session=s)
        s.commit_transaction()
    except Exception:
        s.abort_transaction()

Hope you enjoyed reading the post, please share this post so others can too.
Cheers!!