Search code examples
c#mongodbmongodb-.net-driver

MongoDB multi document transaction, reading non commited data


Until MongoDB v4.0, multi document transactions were achieved by implementing a two phase commit. After 4.0, MongoDB has introduced the multi-document transactions for replica sets; As per their documentation; "until a transaction is committed, no write/update operations in the transaction are visible outside the transaction". But what about the visibility of the data within the transaction scope? For the sake of simplicity, I have implemented the example below, that depicts the case.

            var client = new MongoClient("mongodb://localhost");
            var session = client.StartSession();
            var ColA = session.Client.GetDatabase("Testing").GetCollection<BsonDocument>("ColA");
            JObject Obj = new JObject();
            Obj.Add("A", "ValA");
            session.StartTransaction();
            ColA.InsertOne(session, BsonDocument.Parse(Obj.ToString()));
            var tt = ColA.Find(new BsonDocument { }).ToList();
            session.CommitTransaction();

In the origin, "ColA" is an empty collection, when I insert the document and then try to query it (tt = ColA.Find...), the result set is still empty. I understand that outside the transaction scope, the result set should remain empty until commit, but why is it empty inside the scope.

By reproducing the same scenario on SQL server, using the same logic, querying a table after an insertion within a transaction scope, returns data before commit.

Any Help is appreciated.


Solution

  • It works as you expected, the only thing you're missing in your code is session passed as an argument to Find method, try:

    session.StartTransaction();
    ColA.InsertOne(session, BsonDocument.Parse(Obj.ToString()));
    var tt = ColA.Find(session, Builders<BsonDocument>.Filter.Empty).ToList();
    
    session.CommitTransaction();