How to configure a MongoDB cluster which supports sessions?

I was having the same issue when I was trying to connect it to a single standalone mongo instance, however as written in the official documentation, that Mongo supports transaction feature for a replica set. So, I then tried to create a replica set with all instances on MongoDB 4.0.0, I was able to successfully execute the code. So, Start a replica set (3 members), then try to execute the code, the issue will be resolved.

NB : you can configure a replica set on the same machine for tests https://docs.mongodb.com/manual/tutorial/deploy-replica-set-for-testing/


We were able to config in local as below

  • On Linux, a default /etc/mongod.conf configuration file is included when using a package manager to install MongoDB.

  • On Windows, a default <install directory>/bin/mongod.cfg configuration file is included during the installation

  • On macOS, a default /usr/local/etc/mongod.conf configuration file is included when installing from MongoDB’s official Homebrew tap.

Add the following config

replication:
   oplogSizeMB: 128
   replSetName: "rs0"
   enableMajorityReadConcern: true

sudo service mongod restart;

mongo;

rs.initiate({
      _id: "rs0",
      version: 1,
      members: [
         { _id: 0, host : "localhost:27017" }
      ]
   }
)

check for the config to be enabled

rs.conf()

we can use the connection URL as

mongodb://localhost/default?ssl=false&replicaSet=rs0&readPreference=primary

docs: config-options single-instance-replication