1

In the sample code below, what will happen if retrieved data in the transaction changes(caused by an outside/separated write operation) before it ends or is committed? does the transaction automatically abort?

await session.withTransaction(async () => {
  const coll1 = client.db('mydb1').collection('foo');

  await coll1.find( { qty: { $gt: 4 } }, { session } );
  
  // some code before update
  // if the retrieved data from the above, changed due to a separate write operation, will this transaction abort?

  await coll1.update( 
    { id: 3 },
    { $set: { qty: 2 } },
    { session }
  )

}, transactionOptions);

I read the documentation about the transaction, to my understanding it mostly offers data atomicity and durability, but I can’t find what will happen to a transaction if any read data changed caused by outside/separate write operation

Double
  • 3
  • 3
Paulo
  • 63
  • 6

1 Answers1

0

By default, MongoDB transactions provide snapshot isolation, which ensures that the data read during a transaction is consistent with the data at the beginning of the transaction. The changes that are made to the data outside of the transaction will not show up in the transaction.

Even if separate write operations modify the data, the retrieved data from the coll1.find operation will remain unchanged in the provided code. Regardless of any data modifications made during the transaction, the initial snapshot of the data taken at the beginning of the transaction will continue to be used.

As a result, if separate write operations cause changes to the retrieved data, the transaction will not automatically terminate. It will use the initial snapshot of the data to move forward and will apply any updates or modifications based on that snapshot. Assuming another exchange commits changes to the very information that contentions with the ongoing exchange, then a contention will happen when the ongoing exchange attempts to commit, and the transaction will be rolled back.

So indirectly yes, the transaction will automatically abort if the data it has retrieved changes before it ends or is committed.

Navitas28
  • 745
  • 4
  • 13