Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MongoDB read documents within transaction

Suppose I do the following list of operations in MongoDB

  • Start a session
  • Start a transaction for that session
  • run an insert command with a new document
  • run a find command on the collection of the inserted document
  • Commit the transaction
  • End the session

I understand that outside of the transaction the insert done in the third step will not be visible until the transaction is committed, but what about within the transaction, will the find run in the fourth step see this new document or will it not?

like image 559
Carlos Granados Avatar asked May 21 '26 02:05

Carlos Granados


1 Answers

Yes, a transactional find sees a document inserted in a previous transactional insert. You could assume the Read your own writes property.


Every time a transaction is started a new snapshot is created. Outside the transaction, the snapshot is obviously invisible: this is accomplished by using (and abusing if your transaction involves many updates) the WiredTiger cache. This cache is structured as a tree, similar to the following one1:

wiredtiger cache

where each transactional operation is represented as a new update block that could in turn be chained to another update block.

Outside operations only see non-transactional tree entries, while transactional operations see all the entries added before the snapshot is taken + the update blocks for the given transaction.

I am aware that it is a very brief explanation on how MongoDB manages transaction atomicity, but if you are interested in understanding more on this, then I suggest you to read a report I have written. in the same repository you can find some scenarios for the most typical doubts.


1: image taken from Aly Cabral's presentation about How and when to use Multi-document transactions

like image 158
Marco Luzzara Avatar answered May 23 '26 16:05

Marco Luzzara



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!