How can I lock a document from reading operation for update later in MongoDB

How can I lock a document from reading operation for update later in MongoDB, likes SELECT * FROM mytable WHERE id = 123 FOR UPDATE; in RDBMS

Spring Data MongoDB - Reference Documentation

10.5.10. Optimistic Locking

The @Version annotation provides syntax similar to that of JPA in the context of MongoDB and makes sure updates are only applied to documents with a matching version. Therefore, the actual value of the version property is added to the update query in such a way that the update does not have any effect if another operation altered the document in the meantime. In that case, an OptimisticLockingFailureException is thrown. The following example shows these features:

1 Like

There is a way for Pessimistic ?

Hi @VIRGO_ROMANIA welcome to the community!

There is a blog post for exactly this: How To SELECT ... FOR UPDATE inside MongoDB Transactions | MongoDB Blog

Best regards
Kevin

1 Like