Recommended way to handle write conflicts inside transactions?

Thanks for the reply, it’s true that before introducing transactions, concurrent updates on the same document worked without problems, however it looks like I’m running into the following issue:

https://docs.mongodb.com/manual/core/transactions-production-consideration/#in-progress-transactions-and-write-conflicts.

If a transaction is in progress and a write outside the transaction modifies a document that an operation in the transaction later tries to modify, the transaction aborts because of a write conflict

I’m not sure how to handle this case, since I might have dozens of concurrent transactions writing to the same document.

This is an example that produces write conflicts if run in parallel:

Query query = new Query();
query.addCriteria(Criteria.where("conversationId").is(conversation.getId()));
query.addCriteria(Criteria.where("ownerId").is(receiver.getId()));

Update update = new Update();
update.inc("unreadCount", 1);

mongoTemplate.updateFirst(query, update, Contact.class);
1 Like