Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to locally test MongoDB multicollection transactions when standalone mode does not support them

I am just starting out with MongoDB and am using the docker mongo instance for local development and testing.

My code has to update 2 collections in the same transaction so that the data is logically consistent:

            using (var session = _client.StartSession())
            {
                session.StartTransaction();

                ec.InsertOne(evt);
                sc.InsertMany(snapshot.Selections.Select(ms => new SelectionEntity(snapshot.Id, ms)));

                session.CommitTransaction();

             }

This is failing with the error:

'Standalone servers do not support transactions

The error is obvious, my standalone docker container does not support transactions. I am confused though as this means it's impossible to test code such as the above unless I have a replica set running. This doesn't appear to be listed as a requirement in the documentation - and it refers to the fact that transactions could be multi-document OR distributed:

For situations that require atomicity of reads and writes to multiple documents (in a single or multiple collections), MongoDB supports multi-document transactions. With distributed transactions, transactions can be used across multiple operations, collections, databases, documents, and shards.

It's not clear to me how to create a multi-document transaction that does not require a replica based server to exist or how to properly test code locally that may not have a mongo replica cluster to work against.

How do people handle this?

like image 204
GrahamB Avatar asked Jan 24 '26 16:01

GrahamB


1 Answers

For testing puirposes, you could set up a local replica set using docker-compose. There are various blog posts on the topic available, e.g. Create a replica set in MongoDB with docker-compose.

Another option is to use a cluster on MongoDB Atlas. There is a free tier available so you can test this without any extra cost.

In addition, you could change your code so that transactions can be disabled depending on the configuration. This way, you can test the code without transactions locally and enable them on staging or production.

like image 182
Markus Avatar answered Jan 26 '26 14:01

Markus