How does MongoDB handle transactions?
Why Interviewers Ask This
This is a classic screening question for MongoDB roles. Hiring managers ask it early in interviews to gauge your baseline understanding and determine if you can communicate technical concepts clearly.
Answer
MongoDB added multi-document ACID transactions in version 4.0 (for replica sets) and 4.2 (for sharded clusters). Before this, only single-document operations were atomic. Single-document atomicity: MongoDB has always provided atomic operations on a single document — all fields in a document update atomically. This covers many use cases if data is well-modeled (use embedded documents). Multi-document transactions: for operations spanning multiple documents/collections. Use like a traditional database transaction. Session-based: const session = client.startSession(); session.startTransaction(); try { await users.insertOne({ name: "Alice" }, { session }); await orders.insertOne({ userId: aliceId }, { session }); await session.commitTransaction(); } catch(e) { await session.abortTransaction(); } finally { session.endSession(); }. ACID guarantees: Atomicity (all or nothing), Consistency (constraints enforced), Isolation (read concern "snapshot" — reads a consistent snapshot), Durability (write concern "majority" for durability). Performance considerations: transactions add overhead vs non-transactional operations — MongoDB uses multi-version concurrency control (MVCC). Transactions have a 60-second timeout by default. Keep transactions short. Best practice: first redesign schema to use single-document operations (embedding) — use transactions as a last resort when schema can't be restructured. MongoDB recommends using transactions for multi-document writes that require atomicity.
Pro Tip
Back up your answer with a specific project or situation. Saying 'In my last MongoDB project, I used this when...' immediately makes your answer more credible and memorable.
Previous
What is the MongoDB query language and how does it differ from SQL?
Next
What is the MongoDB Atlas?