Databases 9 min read

MongoDB 4.0 Multi-Document Transactions: Concepts, Configuration, and Code Examples

This article explains MongoDB 4.0's multi-document transaction support, covering replica set limitations, transaction semantics, required settings, read/write concerns, important configuration parameters, client driver versions, and provides practical shell and Python code examples.

NetEase Game Operations Platform
NetEase Game Operations Platform
NetEase Game Operations Platform
MongoDB 4.0 Multi-Document Transactions: Concepts, Configuration, and Code Examples

MongoDB 4.0 introduced multi‑document transaction support, initially only for single replica sets, with sharding support expected in 4.2.

Transactions provide all‑or‑nothing atomicity: changes are invisible outside the transaction until commit, and any failure triggers a rollback.

To use transactions you must run MongoDB 4.0+ with featureCompatibilityVersion set to 4.0; you can verify it with

db.adminCommand({ getParameter: 1, featureCompatibilityVersion: 1 })

. Only the WiredTiger storage engine supports transactions, and MMAPv1 is deprecated.

Example Mongo shell session demonstrates starting a session, creating a transaction, inserting a document, aborting, and committing:

mongodb40:PRIMARY> session = db.getMongo().startSession()
session { "id" : UUID("3bfd3739-caed-4c06-8e61-bfe405658166") }
mongodb40:PRIMARY> trans = session.getDatabase('chenxs').trans
chenxs.trans
mongodb40:PRIMARY> session.startTransaction()
mongodb40:PRIMARY> trans.insert({"a": 3})
WriteResult({ "nInserted" : 1 })
mongodb40:PRIMARY> db.trans.find({a: 3})
mongodb40:PRIMARY> trans.find({a: 3})
{ "_id" : ObjectId("5b5e8579b54570c9fb04ed4c"), "a" : 3 }
mongodb40:PRIMARY> session.abortTransaction()
mongodb40:PRIMARY> session.startTransaction()
mongodb40:PRIMARY> trans.insert({a: 3})
WriteResult({ "nInserted" : 1 })
mongodb40:PRIMARY> db.trans.find({a: 3})
mongodb40:PRIMARY> session.commitTransaction()
mongodb40:PRIMARY> db.trans.find({a: 3})
{ "_id" : ObjectId("5b5e85c3b54570c9fb04ed4d"), "a" : 3 }
mongodb40:PRIMARY>

The example shows that operations on trans and db.trans refer to the same collection, and that only commands executed within the session are part of the transaction.

Sessions, introduced in MongoDB 3.6, provide causal consistency and retryable writes; they are the foundation for transactions in 4.0.

Transaction options include readConcern (local, majority, snapshot) and writeConcern. Both are set at the transaction level; snapshot readConcern is only valid inside multi‑document transactions, and w:0 is prohibited.

Key configurable parameters are transactionLifetimeLimitSeconds (default 60 s) and maxTransactionLockRequestTimeoutMillis (default 5 ms). Setting them to 0 disables waiting, while -1 waits indefinitely.

Additional cautions: collections must exist before use, transactions cannot modify the admin/config/local databases or system.* collections, and cursors created outside a transaction cannot be used inside it.

Performance impact is significant; avoid transactions when possible. Sharding support for transactions is planned for MongoDB 4.2.

Client driver versions that support transactions include Java 3.8.0, Python 3.7.0, C 1.11.0, C# 2.7, and C++ 3.4.x.

Python example using MongoClient and a transaction session illustrates insert, read inside and outside the transaction, and abort:

mc = MongoClient("mongodb://192.168.93.12:27017,192.168.93.18:27017,192.168.93.11:27017/?replicaSet=mongodb40")

with mc.start_session() as session:
    collection = session.client.chenxs.trans
    session.start_transaction()
    collection.insert_one({"a": 14}, session=session)
    result_inside_trans = collection.find_one({"a": 14}, session=session)
    # with transaction session: got a
    print("inside trans before commit, we got: %s" % result_inside_trans)
    result_outside_trans = collection.find_one({"a": 14})
    # without transaction session: got none
    print("outside trans before commit, we got: %s" % result_outside_trans)
    session.abort_transaction()

References to official MongoDB documentation for Transactions, Read Concern, and $count aggregation are provided.

PythondatabasetransactionsMongoDBReadConcernWriteConcern
NetEase Game Operations Platform
Written by

NetEase Game Operations Platform

The NetEase Game Automated Operations Platform delivers stable services for thousands of NetEase titles, focusing on efficient ops workflows, intelligent monitoring, and virtualization.

0 followers
Reader feedback

How this landed with the community

Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.