C# Transactions and Unique Indexes

I’ve found an issue with inserts to a collection with a unique index constraint within a transaction. This only fails when there are concurrent actions to insert the same unique index. My session is enlisting with System.Transaction.Current.

The problem is when two threads with separate transactions both try to insert a document with the same unique index - the InsertOneAsync method completes and other actions (publishing to the bus) in the TransactionScope are executed.

The MongoDB exception raised by the “losing” thread to insert is only raised at the point of calling the Session’s CommitTransation(), however this is too late for the other participants in the wider transaction - as all operations completed, therefore the transaction is deemed “Commitable” and they happily commit.

I understand the the insert isn’t commited to the collection until the transaction is completed - however I need to be able to ensure that the publish isn’t allowed if the CommitTransaction() fails? I need to get the InsertOneAsync method to error at the point of execution.

Many thanks.

Sorry this took so long to reply but I was wondering what would happen here myself.
Testing (not in C# granted) shows it failing on the insert not the commit as that’s the only time MongoDB can detect it - the insert does happen and the check is made.

The only exception is if the collection does not already exist and it’s _id that isn’t unique. In that case it fails on commit with a collection already exists error.

Are you still seeing this as it’s not expected or as far as we can tell possible.