Search code examples
asp.net.netmongodbmongodb-.net-driver

MongoDB Transaction not rollingback correctly


I'm trying to understand MongoDB's transactions so I created this method to play with it:

public async Task<Item> InsertItem(Item item, string appId)
{ 
            var itemAppCollection = _divitiaeDatabase.GetCollection<Item>(appId);
                        
            await itemAppCollection.InsertOneAsync(item);

            return item;
}

public async Task TestyInsertItem(Item item, string appId)
{
            var sessionOptions = new ClientSessionOptions { CausalConsistency = true };
            using (var session = await _divitiaeClient.StartSessionAsync(sessionOptions))
            {
                session.StartTransaction();

                try
                {
                    await InsertItem(item, appId);

                    await InsertItem(item, appId);

                }
                catch (Exception ex)
                {
                    await session.AbortTransactionAsync();
                    throw;
                }
            }              
            
}

I'm basically forcing an error by inserting the same item twice. What I want is that if the second InsertItem fails, the first one should be reverted by throwing an AbortTransactionAsync. Well, the thing is that the error occurs and the AbortTransactionAsync is thrown, but the first insert is not reverted at all, if I check the database I can see that it is still stored there.

What am I doing wrong here? Thanks in advance for the help!


Solution

  • To make transaction work, you should pass a corresponding session instance to all operations (insert accepts a session as input argument) where you expect transaction effect.