Search code examples
c#mongodbtransactionsmongodb-.net-driver

Mongo DB with C# - document added regardless of transaction


I'm trying to test the newly supported transactions in Mongo DB with a simple example I wrote. I'm using Mongo DB version 4.0.5 with driver version 2.8.1. It's only a primary instance with no shards/replicas.

I must be missing something basic in the following code. I create a Mongo client, session & database, then start a transaction, add a document and abort the transaction. After this code, I expect nothing to change in the database, but the document is added. When debugging I can also see the document right after the InsertOne() by using Robo 3T (Mongo client GUI).

Any idea what am I missing?

        var client =  new MongoClient("mongodb://localhost:27017");
        var session = client.StartSession();
        var database = session.Client.GetDatabase("myDatabase", new MongoDatabaseSettings
        {
            GuidRepresentation = GuidRepresentation.Standard,
            ReadPreference = ReadPreference.Primary,
            WriteConcern = new WriteConcern(1, 
                new MongoDB.Driver.Optional<TimeSpan?>(TimeSpan.FromSeconds(30))),

        });

        var entities = database.GetCollection<MyEntity>("test");            

        session.StartTransaction();

        // After this line I can already see the document in the db collection using Mongo client GUI (Robo 3T), although I expect not to see it until committing
        entities.InsertOne(new MyEntity { Name =  "Entity" });

        // This does not have any effect
        session.AbortTransaction();

Edit:

It's possible to run MongoDB as a 1-node replica set, although I'm not sure what's the difference between a standalone and a 1-node replica set. See my post below.

In any case, to use the started transaction the insertion code must receive the session as a parameter:

entities.InsertOne(session, new MyEntity { Name = "Entity" });

With these 2 change now the transaction works.


Solution

  • This is inherently a property of MongoDB itself. (More here and here)

    Transactions are only available in a replica set setup

    Why isnt it available for standalone instances?

    With subdocuments and arrays, document databases (MongoDB) allow related data to be unified hierarchically inside a single data structure. The document can be updated with an atomic operation, giving it the same data integrity guarantees as a multi-table transaction in a relational database.