Search code examples
c#mongodbtransactions

System.NotSupportedException with MongoDb C# Transactions


I am trying to move data from one collection to another collection. So I add a RequestProcess object to the completedRequestsCollection and remove it from the ongoingRequestsCollection. It makes sense to use a transaction to do this so that it can be rolled back if there are issues with either operation.

I found this Mongo Db How-to Guide and tried to follow it, see code below:

//connect to db and get collections
var mongoClient = new MongoClient(connectionString);
var mongoDb = mongoClient.GetDatabase(databaseName);
var ongoingRequestsCollection = mongoDb.GetCollection<RequestProcess>(ongoingRequestsCollectionName);
var completedRequestsCollection = mongoDb.GetCollection<RequestProcess>(completedRequestsCollectionName);

//create session
using var session = mongoClient.StartSession();

//start the transaction
session.StartTransaction();
try
{
    //add to completed requests collection
    await completedRequestsCollection.InsertOneAsync(requestObject);

    //delete from ongoing requests collection
    await ongoingRequestsCollection.DeleteOneAsync(req => req.Id == requestObject.Id);

    //commit transaction
    await session.CommitTransactionAsync();
}
catch (Exception)
{
    //abort transaction
    await session.AbortTransactionAsync();

    //throw the exception to handle further up the stack (knowing that the transaction failed)
    throw;
}

It keeps failing at the session.StartTransaction() line with an Exception as shown below.

Exception thrown: 'System.NotSupportedException' in MongoDB.Driver.Core.dll

Any idea what I'm doing wrong? I know the connection to the database is fine, because I can perform reads, writes and deletes. It just will not perform this transaction but if I remove the transaction related functionality it works fine.


Solution

  • you should provide the whole exception message not only type, it often allows to understand more details. Based on just the exception type, you have either:

    1. You use a standalone mongod server that doesn't support transactions.
    2. You have no available mongod/mongos servers. If it's constant behavior and you can run any other operation (find/insert/ping and etc) this is not your case.

    I would vote that you use a standlone server, so you should replace it on replica set or sharded server configuration.