Using triggers and transactions

Hi Team

What is the recommended approach for utilizing triggers within a transaction to update multiple collections in MongoDB?
In MongoDB, if a trigger fails, will the operations performed on all collections within the transaction be rolled back?

Hi, do you mind clarifying a little bit more what you are looking to accomplish?

It sounds like you are asking what happens to a trigger if it is processing writes from a transaction and fails halfway through. If that is what you are asking, the answer is that the trigger has already fired for the first few events so there is no way for the system to roll back those events being seen. It is possible to uphold this invariant on the developers’ end by utilizing the txnNumber field in the change event https://www.mongodb.com/docs/manual/reference/change-events/insert/#mongodb-data-insert and having your function logic be capable of determining whether it is the end of the transaction or the middle and only firing at the end.

Alternatively, if you are asking what happens if your trigger function code uses a transaction to update documents if that function fails halfway through, then the transaction will indeed be rolled back as long as the function does not issue a commit transaction command (this is just MongoDB doing the work).

Let me know if this answers your question.
Tyler

Hi Tyler,
I have three collections: collection A, collection B, and collection C.
Collection A has a trigger that is invoked when a document is updated it updates records in collection B and collection C.

If the trigger fails I need to roll back the updating in collection A

I’m asking because a trigger’s response to an operation will always be out of the scope of the original operation and I want the db with data consistency and integrity

You are correct that a trigger is a response to an action that has already been performed in MongoDB. You could try to (depending on the change) wrap your function in a try/catch where the catch block performs an un-do of the operation (see PreImages for triggers); however, there will be edge cases in which this will not always 100% run.

The only way to ensure the 3 writes are made transactionally is to perform them in a single MongoDB transaction. One option might be to use custom https endpoints (https://www.mongodb.com/docs/atlas/app-services/data-api/custom-endpoints/) and you can define a function that updates collection A, B, and C in a transaction, and then you can have that be the only entry point for updates to Collection A (or you can just do this in your application code)

Best,
Tyler

3 Likes

so one solution could be a transaction within a try block inside the trigger function,
If an error is caught, I could use the document preimages to roll back the changes
is it the correct solution?