Junior — Middle
What methods does MongoDB support for transaction execution?
sobes.tech AI
Answer from AI
MongoDB supports transactions in two main modes:
-
Single-document transactions — operations within a single document are atomic by default. This means that changes in one document are either fully applied or not applied at all.
-
Multi-document transactions — starting from MongoDB version 4.0, transactions that encompass multiple documents and collections are supported, including operations within one or more databases. Such transactions ensure atomicity, consistency, isolation, and durability (ACID).
Example of using a multi-document transaction in Python with PyMongo:
from pymongo import MongoClient
client = MongoClient()
db = client.testdb
with client.start_session() as session:
with session.start_transaction():
db.collection1.insert_one({'item': 'apple'}, session=session)
db.collection2.update_one({'item': 'banana'}, {'$inc': {'qty': -1}}, session=session)
Thus, MongoDB supports both atomic operations at the single-document level and transactions that encompass multiple operations and documents.