Sobes.tech
Middle

Is it possible to perform atomic operations across multiple documents in MongoDB?

sobes.tech AI

Answer from AI

In MongoDB, atomic operations are guaranteed only at the level of a single document. This means that changes within one document are either fully completed or not executed at all.

If you need to perform atomic operations involving multiple documents, it was impossible in MongoDB before version 4.0. Starting from version 4.0, support for multi-document transactions was introduced, allowing atomic operations on multiple documents within a single transaction.

Example of using a 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.update_one({'_id': 1}, {'$set': {'field': 'value'}}, session=session)
        db.collection2.update_one({'_id': 2}, {'$inc': {'counter': 1}}, session=session)

Thus, atomicity across multiple documents is achieved through transactions, starting from MongoDB 4.0.