DB/Nosql

MongoDB Transactions

데먕 2020. 2. 23. 20:18

1. Overview

With multi-document ACID transactions in MongoDB, you get the only database that fully combines the power of the document model and a distributed systems architecture with ACID guarantees. Through snapshot isolation, transactions provide a consistent view of data and enforce all-or-nothing execution to maintain data integrity, even across sharded clusters.

2. Description

Now for a transaction, we need a so-called session. We haven't worked with sessions before but a session basically means that all our requests are grouped together logically you could say.

const session = db.getMongo().startSession()
session.startTransaction()
const usersCol = session.getDatabase("blog").users
const postsCol = session.getDatabase("blog").posts

usersCol.deleteOne({_id: ObjectId("5e52617809703d91e9e44444")})
postsCol.deleteMany({userId: ObjectId("5e52617809703d91e9e44444")})
session.commitTransaction()

3. Reference

https://www.mongodb.com/transactions

https://docs.mongodb.com/manual/core/transactions/