Similar to using transaction logging statements in structured databases (Begin work, Rollback work/Commit work) How to we do the same in unstructured database like mongoDB

Similar to using transaction logging statements in structured databases (Begin work, Rollback work/Commit work) How to we do the same in unstructured database like mongoDB. Kindly guide.

Welcome to the MongoDB Community @Kavita_Mhatre_1!

Support for multi-document transactions in replica sets was first added in MongoDB 4.0 and expanded in successive releases to support sharded clusters and additional features. I recommend using a 4.2+ version of MongoDB server and an official driver (or library depending on an official driver) that is fully compatible.

NOTE: multi-document transactions require a replica set or sharded cluster deployment.

The documentation page embeds examples for most MongoDB drivers. The concept is analogous to SQL transactions: you start a transaction in a session and either commit or rollback.

Here’s an example using the MongoDB shell:

// Start a session.
session = db.getMongo().startSession( { readPreference: { mode: "primary" } } );
coll1 = session.getDatabase("mydb1").foo;
coll2 = session.getDatabase("mydb2").bar;

// Start a transaction
session.startTransaction( { readConcern: { level: "local" }, writeConcern: { w: "majority" } } );

// Operations inside the transaction
try {
   coll1.insertOne( { abc: 1 } );
   coll2.insertOne( { xyz: 999 } );
} catch (error) {
   // Abort transaction on error
   session.abortTransaction();
   throw error;
}

// Commit the transaction using write concern set at transaction start
session.commitTransaction();
session.endSession();

Regards,
Stennie