🍃 MongoDB Intermediate

What is MongoDB's approach to concurrency?

Answer

MongoDB (with WiredTiger) uses Multi-Version Concurrency Control (MVCC) and document-level locking for fine-grained concurrency. Lock types: (1) Document-level locks: the default for WiredTiger — a write to document A doesn't block reads or writes to document B in the same collection. Much better than old collection-level locking; (2) Collection-level locks: certain operations lock the entire collection (e.g., creating/dropping an index, collection rename); (3) Database-level locks: some administrative operations; (4) Global-level locks: rare — some global maintenance operations. Intent locks: MongoDB uses intent lock hierarchy — before taking a document lock, acquires intent locks at collection and database levels (allows multiple concurrent document locks while exclusive collection-level operations can still be expressed). MVCC behavior: readers see a consistent snapshot (as of the start of their read), not blocked by concurrent writers; writers operate on the current version; concurrent writers to the same document block each other (first-write-wins with retry). Transactions: multi-document transactions use optimistic concurrency by default for reads (no read locks) but acquire write locks when modifying documents. Lock yield: long operations yield locks to allow other operations through. Monitoring: db.serverStatus().globalLock shows lock stats; db.currentOp() shows lock status per operation. WiredTiger's MVCC makes MongoDB well-suited for mixed read-write workloads.