What is MongoDB Transaction?

Code With Travel
1 min readFeb 28, 2021

--

Let’s suppose we have 2 collections of users and posts. If we want to delete all related posts of the user when we delete the user. We can manage this thing by following steps.
First, we delete users and after that, we delete all posts related to that user from posts collection. But somehow we get errors during deleting posts from the collection. In such cases, the user is removed but posts remain in the collection. To handle such a scenario Transaction comes into place.

Let’s take an example. Insert data to users and posts collection.

db.users.insertOne({"name":"lorem"});

Copy inserted Id and use it to insert posts.

db.posts.insertMany([{"title":"First post", userId :  ObjectId("603a0f6386ec4a11774ff40d")},{"title":"Second post",userId: ObjectId("603a0f6386ec4a11774ff40d")}])

After that let’s create a session, start a session, register some constants.

const session = db.getMongo().startSession();
const postCol = session.getDatabase("blog").posts;
const userCol = session.getDatabase("blog").users;
session.startTransaction();
userCol.deleteOne({_id : ObjectId("603a0f6386ec4a11774ff40d")});
postCol.deleteMany({userId : ObjectId("603a0f6386ec4a11774ff40d")});
session.commitTransaction();

I hope it will help you.

--

--

No responses yet