Is there any way to simulate an update operation?

I would like to know if it is possible to simulate the result of an updateOne or updateMany operation without persisting the changes and get the result, but I did not found any way to do this. ¿Is there any way to do it without performing a local hard code update in a document locally?

Thank you.

You could try doing this within a transaction and then rolling back?

https://www.mongodb.com/docs/drivers/node/v4.1/fundamentals/transactions/#:~:text=In%20MongoDB%2C%20multi-document%20transactions,a%20new%20client%20each%20time.

An alternate way could be the use of change streams.

You may then use the pre-image of the document in your stream listener to revert the change.

The risk of an infinite look is high if your code tries to revert the changes you are trying to revert.

First of all, thank you for your answers John_Sewell and Steeve.

Finally I decided to use aggregations. I thought that the modifications made by $set operator modifying matching documents after a $match pipeline were persisted in the database. It was just my lack of knowledge about aggregations. This method solved my problem.

Thank you very much and I hope this is useful for anyone having the same doubt!

1 Like