Spring Mongodb Concurrent Upsert

I’d like to insert or update a document in MongoDB based on if a document with that id already exists.

I am using MongoOperations to do this upsert.

(This is called twice in my application) I am using the command mongoOperations.upsert(query, update, Transation.class)

Desired Behavior : Insert if an transaction id does not exist else update.

Actual Behavior : Works as expected except in some scenarios where one upsert command is overwritten by the other upsert.

I suspect this is happening because there are two instances running and in some scenarios both instances read the db when ID is not inserted and both try to insert.

According to SERVER-14322 (https://jira.mongodb.org/browse/SERVER-14322) the second upsert command should ideally throw Duplicate key exception and then mongodb should try to run the command again, In my case I dont see any exceptions but the data of one upsert command is lost.

(I am using Mongo 4.2 and Spring-data-mongo 1.7.2)