Transactions

In MongoDB, an operation on a single document is atomic. Because you canuse embedded documents and arrays to capture relationships between datain a single document structure instead of normalizing across multipledocuments and collections, this single-document atomicity obviates theneed for multi-document transactions for many practical use cases.

For situations that require atomicity of reads and writes to multipledocuments (in a single or multiple collections), MongoDB supportsmulti-document transactions. With distributed transactions,transactions can be used across multiple operations, collections,databases, documents, and shards.

Transactions API

The following example highlights the key componentsof the transactions API:

  • Python
  • Java
  • Node.js
  • PHP
  • C#
  • Other
    • mongo Shell

The example uses the new callback API for working withtransactions, which starts a transaction, executes thespecified operations, and commits (or aborts on error). Thenew callback API also incorporates retry logic forTransientTransactionError orUnknownTransactionCommitResult commit errors.

Important

  • For transactions on MongoDB 4.2 deployments (replicasets and sharded clusters), clients must useMongoDB drivers updated for MongoDB 4.2.
  • When using the drivers, each operation in thetransaction must be associated with the session (i.e.pass in the session to each operation).
  1. # For a replica set, include the replica set name and a seedlist of the members in the URI string; e.g.
  2. # uriString = 'mongodb://mongodb0.example.com:27017,mongodb1.example.com:27017/?replicaSet=myRepl'
  3. # For a sharded cluster, connect to the mongos instances; e.g.
  4. # uriString = 'mongodb://mongos0.example.com:27017,mongos1.example.com:27017/'
  5.  
  6. client = MongoClient(uriString)
  7. wc_majority = WriteConcern("majority", wtimeout=1000)
  8.  
  9. # Prereq: Create collections. CRUD operations in transactions must be on existing collections.
  10. client.get_database(
  11. "mydb1", write_concern=wc_majority).foo.insert_one({'abc': 0})
  12. client.get_database(
  13. "mydb2", write_concern=wc_majority).bar.insert_one({'xyz': 0})
  14.  
  15. # Step 1: Define the callback that specifies the sequence of operations to perform inside the transactions.
  16. def callback(session):
  17. collection_one = session.client.mydb1.foo
  18. collection_two = session.client.mydb2.bar
  19.  
  20. # Important:: You must pass the session to the operations.
  21. collection_one.insert_one({'abc': 1}, session=session)
  22. collection_two.insert_one({'xyz': 999}, session=session)
  23.  
  24. # Step 2: Start a client session.
  25. with client.start_session() as session:
  26. # Step 3: Use with_transaction to start a transaction, execute the callback, and commit (or abort on error).
  27. session.with_transaction(
  28. callback, read_concern=ReadConcern('local'),
  29. write_concern=wc_majority,
  30. read_preference=ReadPreference.PRIMARY)
  31.  

The example uses the new callback API for working withtransactions, which starts a transaction, executes thespecified operations, and commits (or aborts on error). Thenew callback API also incorporates retry logic forTransientTransactionError orUnknownTransactionCommitResult commit errors.

Important

  • For transactions on MongoDB 4.2 deployments (replicasets and sharded clusters), clients must useMongoDB drivers updated for MongoDB 4.2.
  • When using the drivers, each operation in thetransaction must be associated with the session (i.e.pass in the session to each operation).
  1. /*
  2. For a replica set, include the replica set name and a seedlist of the members in the URI string; e.g.
  3. String uri = "mongodb://mongodb0.example.com:27017,mongodb1.example.com:27017/admin?replicaSet=myRepl";
  4. For a sharded cluster, connect to the mongos instances; e.g.
  5. String uri = "mongodb://mongos0.example.com:27017,mongos1.example.com:27017:27017/admin";
  6. */
  7.  
  8. final MongoClient client = MongoClients.create(uri);
  9.  
  10. /*
  11. Prereq: Create collections. CRUD operations in transactions must be on existing collections.
  12. */
  13.  
  14. client.getDatabase("mydb1").getCollection("foo")
  15. .withWriteConcern(WriteConcern.MAJORITY).insertOne(new Document("abc", 0));
  16. client.getDatabase("mydb2").getCollection("bar")
  17. .withWriteConcern(WriteConcern.MAJORITY).insertOne(new Document("xyz", 0));
  18.  
  19. /* Step 1: Start a client session. */
  20.  
  21. final ClientSession clientSession = client.startSession();
  22.  
  23. /* Step 2: Optional. Define options to use for the transaction. */
  24.  
  25. TransactionOptions txnOptions = TransactionOptions.builder()
  26. .readPreference(ReadPreference.primary())
  27. .readConcern(ReadConcern.LOCAL)
  28. .writeConcern(WriteConcern.MAJORITY)
  29. .build();
  30.  
  31. /* Step 3: Define the sequence of operations to perform inside the transactions. */
  32.  
  33. TransactionBody txnBody = new TransactionBody<String>() {
  34. public String execute() {
  35. MongoCollection<Document> coll1 = client.getDatabase("mydb1").getCollection("foo");
  36. MongoCollection<Document> coll2 = client.getDatabase("mydb2").getCollection("bar");
  37.  
  38. /*
  39. Important:: You must pass the session to the operations.
  40. */
  41. coll1.insertOne(clientSession, new Document("abc", 1));
  42. coll2.insertOne(clientSession, new Document("xyz", 999));
  43. return "Inserted into collections in different databases";
  44. }
  45. };
  46. try {
  47. /*
  48. Step 4: Use .withTransaction() to start a transaction,
  49. execute the callback, and commit (or abort on error).
  50. */
  51.  
  52. clientSession.withTransaction(txnBody, txnOptions);
  53. } catch (RuntimeException e) {
  54. // some error handling
  55. } finally {
  56. clientSession.close();
  57. }

The example uses the new callback API for working withtransactions, which starts a transaction, executes thespecified operations, and commits (or aborts on error). Thenew callback API also incorporates retry logic forTransientTransactionError orUnknownTransactionCommitResult commit errors.

Important

  • For transactions on MongoDB 4.2 deployments (replicasets and sharded clusters), clients must useMongoDB drivers updated for MongoDB 4.2.
  • When using the drivers, each operation in thetransaction must be associated with the session (i.e.pass in the session to each operation).
  1. // For a replica set, include the replica set name and a seedlist of the members in the URI string; e.g.
  2. // const uri = 'mongodb://mongodb0.example.com:27017,mongodb1.example.com:27017/?replicaSet=myRepl'
  3. // For a sharded cluster, connect to the mongos instances; e.g.
  4. // const uri = 'mongodb://mongos0.example.com:27017,mongos1.example.com:27017/'
  5.  
  6. const client = new MongoClient(uri);
  7. await client.connect();
  8.  
  9. // Prereq: Create collections. CRUD operations in transactions must be on existing collections.
  10.  
  11. await client
  12. .db('mydb1')
  13. .collection('foo')
  14. .insertOne({ abc: 0 }, { w: 'majority' });
  15.  
  16. await client
  17. .db('mydb2')
  18. .collection('bar')
  19. .insertOne({ xyz: 0 }, { w: 'majority' });
  20.  
  21. // Step 1: Start a Client Session
  22. const session = client.startSession();
  23.  
  24. // Step 2: Optional. Define options to use for the transaction
  25. const transactionOptions = {
  26. readPreference: 'primary',
  27. readConcern: { level: 'local' },
  28. writeConcern: { w: 'majority' }
  29. };
  30.  
  31. // Step 3: Use withTransaction to start a transaction, execute the callback, and commit (or abort on error)
  32. // Note: The callback for withTransaction MUST be async and/or return a Promise.
  33. try {
  34. await session.withTransaction(async () => {
  35. const coll1 = client.db('mydb1').collection('foo');
  36. const coll2 = client.db('mydb2').collection('bar');
  37.  
  38. // Important:: You must pass the session to the operations
  39.  
  40. await coll1.insertOne({ abc: 1 }, { session });
  41. await coll2.insertOne({ xyz: 999 }, { session });
  42. }, transactionOptions);
  43. } finally {
  44. await session.endSession();
  45. await client.close();
  46. }

The example uses the new callback API for working withtransactions, which starts a transaction, executes thespecified operations, and commits (or aborts on error). Thenew callback API also incorporates retry logic forTransientTransactionError orUnknownTransactionCommitResult commit errors.

Important

  • For transactions on MongoDB 4.2 deployments (replicasets and sharded clusters), clients must useMongoDB drivers updated for MongoDB 4.2.
  • When using the drivers, each operation in thetransaction must be associated with the session (i.e.pass in the session to each operation).
  1. /*
  2. * For a replica set, include the replica set name and a seedlist of the members in the URI string; e.g.
  3. * uriString = 'mongodb://mongodb0.example.com:27017,mongodb1.example.com:27017/?replicaSet=myRepl'
  4. * For a sharded cluster, connect to the mongos instances; e.g.
  5. * uriString = 'mongodb://mongos0.example.com:27017,mongos1.example.com:27017/'
  6. */
  7.  
  8. $client = new \MongoDB\Client($uriString);
  9.  
  10. // Prerequisite: Create collections. CRUD operations in transactions must be on existing collections.
  11. $client->selectCollection(
  12. 'mydb1',
  13. 'foo',
  14. [
  15. 'writeConcern' => new \MongoDB\Driver\WriteConcern(\MongoDB\Driver\WriteConcern::MAJORITY, 1000),
  16. ]
  17. )->insertOne(['abc' => 0]);
  18.  
  19. $client->selectCollection(
  20. 'mydb2',
  21. 'bar',
  22. [
  23. 'writeConcern' => new \MongoDB\Driver\WriteConcern(\MongoDB\Driver\WriteConcern::MAJORITY, 1000),
  24. ]
  25. )->insertOne(['xyz' => 0]);
  26.  
  27. // Step 1: Define the callback that specifies the sequence of operations to perform inside the transactions.
  28.  
  29. $callback = function (\MongoDB\Driver\Session $session) use ($client) {
  30. $client
  31. ->selectCollection('mydb1', 'foo')
  32. ->insertOne(['abc' => 1], ['session' => $session]);
  33.  
  34. $client
  35. ->selectCollection('mydb2', 'bar')
  36. ->insertOne(['xyz' => 999], ['session' => $session]);
  37. };
  38.  
  39. // Step 2: Start a client session.
  40.  
  41. $session = $client->startSession();
  42.  
  43. // Step 3: Use with_transaction to start a transaction, execute the callback, and commit (or abort on error).
  44.  
  45. $transactionOptions = [
  46. 'readConcern' => new \MongoDB\Driver\ReadConcern(\MongoDB\Driver\ReadConcern::LOCAL),
  47. 'writeConcern' => new \MongoDB\Driver\WriteConcern(\MongoDB\Driver\WriteConcern::MAJORITY, 1000),
  48. 'readPreference' => new \MongoDB\Driver\ReadPreference(\MongoDB\Driver\ReadPreference::RP_PRIMARY),
  49. ];
  50.  
  51. \MongoDB\with_transaction($session, $callback, $transactionOptions);

The example uses the new callback API for working withtransactions, which starts a transaction, executes thespecified operations, and commits (or aborts on error). Thenew callback API also incorporates retry logic forTransientTransactionError orUnknownTransactionCommitResult commit errors.

Important

  • For transactions on MongoDB 4.2 deployments (replicasets and sharded clusters), clients must useMongoDB drivers updated for MongoDB 4.2.
  • When using the drivers, each operation in thetransaction must be associated with the session (i.e.pass in the session to each operation).
  1. // For a replica set, include the replica set name and a seedlist of the members in the URI string; e.g.
  2. // string uri = "mongodb://mongodb0.example.com:27017,mongodb1.example.com:27017/?replicaSet=myRepl";
  3. // For a sharded cluster, connect to the mongos instances; e.g.
  4. // string uri = "mongodb://mongos0.example.com:27017,mongos1.example.com:27017/";
  5. var client = new MongoClient(connectionString);
  6.  
  7. // Prereq: Create collections. CRUD operations in transactions must be on existing collections.
  8. var database1 = client.GetDatabase("mydb1");
  9. var collection1 = database1.GetCollection<BsonDocument>("foo").WithWriteConcern(WriteConcern.WMajority);
  10. collection1.InsertOne(new BsonDocument("abc", 0));
  11.  
  12. var database2 = client.GetDatabase("mydb2");
  13. var collection2 = database2.GetCollection<BsonDocument>("bar").WithWriteConcern(WriteConcern.WMajority);
  14. collection2.InsertOne(new BsonDocument("xyz", 0));
  15.  
  16. // Step 1: Start a client session.
  17. using (var session = client.StartSession())
  18. {
  19. // Step 2: Optional. Define options to use for the transaction.
  20. var transactionOptions = new TransactionOptions(
  21. readPreference: ReadPreference.Primary,
  22. readConcern: ReadConcern.Local,
  23. writeConcern: WriteConcern.WMajority);
  24.  
  25. // Step 3: Define the sequence of operations to perform inside the transactions
  26. var cancellationToken = CancellationToken.None; // normally a real token would be used
  27. result = session.WithTransaction(
  28. (s, ct) =>
  29. {
  30. collection1.InsertOne(s, new BsonDocument("abc", 1), cancellationToken: ct);
  31. collection2.InsertOne(s, new BsonDocument("xyz", 999), cancellationToken: ct);
  32. return "Inserted into collections in different databases";
  33. },
  34. transactionOptions,
  35. cancellationToken);
  36. }

Note

The mongo shell example omits retry logicand robust error handling for simplicity’s sake. For amore practical example of incorporating transactions inapplications, see Transaction Error Handling instead.

  1. // Prereq: Create collections. CRUD operations in transactions must be on existing collections.
  2. db.getSiblingDB("mydb1").foo.insert( {abc: 0}, { writeConcern: { w: "majority", wtimeout: 2000 } } );
  3. db.getSiblingDB("mydb2").bar.insert( {xyz: 0}, { writeConcern: { w: "majority", wtimeout: 2000 } } );
  4.  
  5. // Start a session.
  6. session = db.getMongo().startSession( { readPreference: { mode: "primary" } } );
  7.  
  8. coll1 = session.getDatabase("mydb1").foo;
  9. coll2 = session.getDatabase("mydb2").bar;
  10.  
  11. // Start a transaction
  12. session.startTransaction( { readConcern: { level: "local" }, writeConcern: { w: "majority" } } );
  13.  
  14. // Operations inside the transaction
  15. try {
  16. coll1.insertOne( { abc: 1 } );
  17. coll2.insertOne( { xyz: 999 } );
  18. } catch (error) {
  19. // Abort transaction on error
  20. session.abortTransaction();
  21. throw error;
  22. }
  23.  
  24. // Commit the transaction using write concern set at transaction start
  25. session.commitTransaction();
  26.  
  27. session.endSession();

Transactions and Atomicity

For situations that require atomicity of reads and writes to multipledocuments (in a single or multiple collections), MongoDB supportsmulti-document transactions:

  • In version 4.0, MongoDB supports multi-document transactions onreplica sets.

  • In version 4.2, MongoDB introduces distributed transactions,which adds support for multi-document transactions on shardedclusters and incorporates the existing support formulti-document transactions on replica sets.

To use transactions on MongoDB 4.2 deployments(replica sets andsharded clusters), clients must use MongoDB drivers updated forMongoDB 4.2.

Multi-document transactions are atomic (i.e. provide an“all-or-nothing” proposition):

  • When a transaction commits, all data changes made in the transactionare saved and visible outside the transaction. That is, a transactionwill not commit some of its changes while rolling back others.

Until a transaction commits, the data changes made in thetransaction are not visible outside the transaction.

However, when a transaction writes to multiple shards, not alloutside read operations need to wait for the result of the committedtransaction to be visible across the shards. For example, if atransaction is committed and write 1 is visible on shard A but write2 is not yet visible on shard B, an outside read at read concern"local" can read the results of write 1 withoutseeing write 2.

  • When a transaction aborts, all data changes made in the transactionare discarded without ever becoming visible. For example, if anyoperation in the transaction fails, the transaction aborts and alldata changes made in the transaction are discarded without everbecoming visible.

Important

In most cases, multi-document transaction incurs a greaterperformance cost over single document writes, and theavailability of multi-document transactions should not be areplacement for effective schema design. For many scenarios, thedenormalized data model (embedded documents and arrays) will continue to be optimal for yourdata and use cases. That is, for many scenarios, modeling your dataappropriately will minimize the need for multi-documenttransactions.

For additional transactions usage considerations(such as runtime limit and oplog size limit), see alsoProduction Considerations.

See also

Outside Reads During Commit

Transactions and Operations

Distributed transactions can be used across multiple operations,collections, databases, documents, and, starting in MongoDB 4.2, shards.

For transactions:

  • You can specify read/write (CRUD) operations on existingcollections. The collections can be in different databases. For alist of CRUD operations, see CRUD Operations.
  • You cannot write to cappedcollections. (Starting in MongoDB 4.2)
  • You cannot read/write to collections in the config, admin,or local databases.
  • You cannot write to system.* collections.
  • You cannot return the supported operation’s query plan (i.e. explain).
  • For cursors created outside of a transaction, you cannot callgetMore inside the transaction.
  • For cursors created in a transaction, you cannot callgetMore outside the transaction.
  • Starting in MongoDB 4.2, you cannot specify killCursors asthe first operation in a transaction.

Operations that affect the database catalog, such as creating ordropping a collection or an index, are not allowed intransactions. For example, a transaction cannot include an insertoperation that would result in the creation of a new collection. SeeRestricted Operations.

Tip

When creating or dropping a collection immediately beforestarting a transaction, if the collection is accessed within thetransaction, issue the create or drop operation with writeconcern "majority" to ensure that the transactioncan acquire the required locks.

See also

Count Operation

To perform a count operation within a transaction, use the$count aggregation stage or the $group (with a$sum expression) aggregation stage.

MongoDB drivers compatible with the 4.0 features provide acollection-level API countDocuments(filter, options) as a helpermethod that uses the $group with a $sum expressionto perform a count. The 4.0 drivers have deprecated the count() API.

Starting in MongoDB 4.0.3, the mongo shell provides thedb.collection.countDocuments() helper method that uses the$group with a $sum expression to perform a count.

Distinct Operation

To perform a distinct operation within a transaction:

To find the distinct values for a sharded collection, use theaggregation pipeline with the $group stage instead.For example:

  • Instead of db.coll.distinct("x"), use
  1. db.coll.aggregate([
  2. { $group: { _id: null, distinctValues: { $addToSet: "$x" } } },
  3. { $project: { _id: 0 } }
  4. ])
  • Instead of db.coll.distinct("x", { status: "A" }), use:
  1. db.coll.aggregate([
  2. { $match: { status: "A" } },
  3. { $group: { _id: null, distinctValues: { $addToSet: "$x" } } },
  4. { $project: { _id: 0 } }
  5. ])

The pipeline returns a cursor to a document:

  1. { "distinctValues" : [ 2, 3, 1 ] }

Iterate the cursor to access the results document.

Informational Operations

Informational commands, such as isMaster,buildInfo, connectionStatus (and theirhelper methods) are allowed in transactions; however, they cannot bethe first operation in the transaction.

Restricted Operations

The following operations are not allowed in transactions:

  • Operations that affect the database catalog, such as creating ordropping a collection or an index. For example, atransaction cannot include an insert operation that would resultin the creation of a new collection.

The listCollections and listIndexescommands and their helper methods are also excluded.

See also

Transactions and Sessions

  • Transactions are associated with a session; i.e. you start atransaction for a session.
  • At any given time, you can have at most one open transaction for asession.
  • When using the drivers, each operation in the transaction must beassociated with the session. Refer to your driver specificdocumentation for details.
  • If a session ends and it has an open transaction, the transactionaborts.

Read Concern/Write Concern/Read Preference

Transactions and Read Preference

Operations in a transaction use the transaction-level readpreference.

Using the drivers, you can set the transaction-level readpreference at the transaction start:

  • If the transaction-level read preference is unset, the transactionuses the session-level read preference.
  • If transaction-level and the session-level read preference are unset,the transaction uses the client-level read preference. By default,the client-level read preference is primary.

Multi-document transactions that containread operations must use read preference primary. Alloperations in a given transaction must route to the same member.

Transactions and Read Concern

Operations in a transaction use the transaction-level readconcern. That is, any read concern set atthe collection and database level is ignored inside the transaction.

You can set the transaction-level read concern at the transaction start.

  • If the transaction-level read concern is unset, the transaction-levelread concern defaults to the session-level read concern.
  • If transaction-level and the session-level read concern are unset,the transaction-level read concern defaults to the client-level readconcern. By default, client-level read concern is"local" for reads against the primary. See alsoTransactions and Read Preference.

Transactions support the following read concern levels:

"local"

  • Read concern "local" returns the most recent dataavailable from the node but can be rolled back.
  • For transactions on sharded cluster, "local" readconcern cannot guarantee that the data is from the same snapshotview across the shards. If snapshot isolation is required, use"snapshot" read concern.

"majority"

  • Read concern "majority" returns data that has beenacknowledged by a majority of the replica set members (i.e. datacannot be rolled back) if the transaction commits withwrite concern “majority”.
  • If the transaction does not use write concern “majority” for the commit, the"majority" read concern provides no guarantees thatread operations read majority-committed data.
  • For transactions on sharded cluster, "majority" readconcern cannot guarantee that the data is from the same snapshotview across the shards. If snapshot isolation is required, use"snapshot" read concern.

"snapshot"

Transactions and Write Concern

Transactions use the transaction-level write concern to commit the write operations. Writeoperations inside transactions must be issued without explicit writeconcern specification and use the default write concern. At committime, the writes are then commited using the transaction-level writeconcern.

Tip

Do not explicitly set the write concern for the individual writeoperations inside a transaction. Setting write concerns for theindividual write operations inside a transaction results in an error.

You can set the transaction-level write concern at the transaction start:

  • If the transaction-level write concern is unset, thetransaction-level write concern defaults to the session-level writeconcern for the commit.
  • If the transaction-level write concern and the session-level writeconcern are unset, transaction-level write concern defaults to theclient-level write concern. By default, client-level write concernis w: 1.

Transactions support all write concern wvalues, including:

w: 1

  • Write concern w: 1 returnsacknowledgement after the commit has been applied to the primary.

Important

When you commit with w: 1, yourtransaction can be rolled back if there is a failover.

  • When you commit with w: 1 writeconcern, transaction-level "majority" read concernprovides no guarantees that read operations in the transactionread majority-committed data.

  • When you commit with w: 1 writeconcern, transaction-level "snapshot" read concernprovides no guarantee that read operations in the transactionused a snapshot of majority-committed data.

w: "majority"

  • Write concern w: "majority" returnsacknowledgement after the commit has been applied to a majority(M) of voting members; i.e. the commit has been applied to theprimary and (M-1) voting secondaries.
  • When you commit with w: "majority"write concern, transaction-level "majority" readconcern guarantees that operations have read majority-committeddata. For transactions on sharded clusters, this view of themajority-committed data is not synchronized across shards.
  • When you commit with w: "majority"write concern, transaction-level "snapshot" readconcern guarantees that operations have from a synchronizedsnapshot of majority-committed data.

General Information

Production Considerations

For various production considerations with using transactions, seeProduction Considerations. In addition, or shardedclusters, see also Production Considerations (Sharded Clusters).

Arbiters

Transactions whose write operations span multiple shards will errorand abort if any transaction operation reads from or writes to ashard that contains an arbiter.

See also Disabled Read Concern Majority for transaction restrictions on shards thathave disabled read concern majority.

Disabled Read Concern Majority

A 3-member PSA (Primary-Secondary-Arbiter) replica set or a shardedcluster with 3-member PSA shards may have disabled read concernmajority (—enableMajorityReadConcern false orreplication.enableMajorityReadConcern: false)

  1. readConcern level 'snapshot' is not supported in sharded clusters when enableMajorityReadConcern=false.
  • Transactions whose write operations span multiple shards willerror and abort if any of the transaction’s read or writeoperations involves a shard that has disabled read concern"majority".

However, if you are planning to transition to a sharded cluster withdisabled read concern majority shards, you may wish to avoid usingread concern "snapshot".

Tip

To check if read concern “majority” is disabled, You can rundb.serverStatus() on the mongod instancesand check the storageEngine.supportsCommittedReadsfield. If false, read concern “majority” is disabled.

For more information, see 3-Member Primary-Secondary-Arbiter Architecture andThree Member Primary-Secondary-Arbiter Shards.

Shard Configuration Restriction

You cannot run transactions on a sharded cluster that has a shardwith writeConcernMajorityJournalDefault set to false(such as a shard with a voting member that uses the in-memorystorage engine).

Diagnostics

MongoDB provides various transactions metrics:

Via
db.serverStatus() methodserverStatus commandReturns transactions metrics.
$currentOp aggregation pipelineReturns:- $currentOp.transaction if an operation is part of atransaction.- Information on inactive sessions that are holding locks as partof a transaction.- $currentOp.twoPhaseCommitCoordinator metrics forsharded transactions that involes writes to multiple shards.
db.currentOp() methodcurrentOp commandReturns:- currentOp.transaction if an operation is part of atransaction.- currentOp.twoPhaseCommitCoordinator metrics forsharded transactions that involes writes to multiple shards.
mongod and mongos log messagesIncludes information on slow transactions (i.e. transactionsthat exceed the operationProfiling.slowOpThresholdMsthreshhold) under the TXN log component.

Feature Compatibility Version (FCV)

To use transactions, the featureCompatibilityVersionfor all members of the deployment must be at least:

DeploymentMinimum featureCompatibilityVersion
Replica Set4.0
Sharded Cluster4.2

To check the fCV for a member, connect to the member and run thefollowing command:

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

For more information, see thesetFeatureCompatibilityVersion reference page.

Storage Engines

Starting in MongoDB 4.2, multi-document transactions are supported on replica sets and shardedclusters where:

  • the primary uses the WiredTiger storage engine, and
  • the secondary members use either the WiredTiger storage engine or thein-memory storage engines.

In MongoDB 4.0, only replica sets using the WiredTiger storageengine supported transactions.

Note

You cannot run transactions on a sharded cluster that has a shardwith writeConcernMajorityJournalDefault set tofalse, such as a shard with a voting member that uses thein-memory storage engine.

Additional Transactions Topics