Tibo
Tibo

Reputation: 61

Mongodb/Nested transactions : open transaction in another one not working

I am using MongoDb 4.2 in my web server. When I open an session/transaction T2 inside a global session/transaction (T1), the commit within the T2 will persist in the database and cannot be canceled in the global transaction T1.

How could we implement this nested transaction ? Should I open only one singleton session in my web server and use it in all updating operations ?

Here is a example :

def remove_order_in_book(self, book, order):
        with self.start_session() as session:
            with session.start_transaction():
                book_collection.delete_one(..)

def remove_book_from_order(self, book):
   with client.start_session() as session:
         with session.start_transaction():
             orders = self.get_orders_of_book (book)
             for order in orders:
                self.remove_order_in_book(book, order)

Thank you for any idea !

Upvotes: 2

Views: 3175

Answers (1)

Wan B.
Wan B.

Reputation: 18835

MongoDB Transactions are associated with a session; At any given time, you can have at most one open transaction for a session.

Looking at your example, you should try to package all of the book order removal in one transaction. You can even use collection.deleteMany() in a transaction.

Also worth noting, that if a session ends and it has an open transaction, the transaction aborts.

Upvotes: 3

Related Questions