I read somewhere that
MongoDB holds db level write lock, does this mean that when someone updates any
collection others are not allowed to read other
collection or how it works. Also when someone writes anything to the db how
MongoDB acquires write lock and what is its granularity?
I read somewhere that
Your interpretation matches the "How granular are locks in MongoDB?" part in MongoDB FAQ:
How granular are locks in MongoDB?
Beginning with version 2.2, MongoDB implements locks on a per-database basis for most read and write operations. Some global operations, typically short lived operations involving multiple databases, still require a global “instance” wide lock. Before 2.2, there is only one “global” lock per mongod instance.
For example, if you have six databases and one takes a write lock, the other five are still available for read and write.
As for the way the locking works:
What type of locking does MongoDB use?
MongoDB uses a readers-writer [ed: also known as “multi-reader” or “shared exclusive”] lock that allows concurrent reads access to a database but gives exclusive access to a single write operation.
When a read lock exists, many read operations may use this lock. However, when a write lock exists, a single write operation holds the lock exclusively, and no other read or write operations may share the lock.
Locks are “writer greedy,” which means writes have preference over reads. When both a read and write are waiting for a lock, MongoDB grants the lock to the write.
The lock scope has been moving in the various MongoDB versions. They're getting closer to the data over time.
- Versions before 2.2 had a global lock per MongoDB instance.
- A lock held on one database on the instance blocked writes to all databases on that instance.
- As of v2.2, this was changed to be a database lock.
- A lock on one collection would block writes to the entire database.
- Collection level locks are on the future feature list but are not yet on the road-map (the JIRA ticket that's tracking this feature).
Mongo is pretty good about lock yielding. The impact of replicating and sharding on the behavior of locks is important if you are building a system that uses those, as the options you choose to implement can affect how much blocking locks affect your system.
From MongoDB version 3.0, locks are available at following granularity levels :
- Global (MongoD instance) – All databases in it are affected by the lock.
- Database – Only the Database on which lock is applied is affected.
- Collection – Only the Collection on which lock is applied is affected.
- Document – Only the Document on which lock is applied is affected.
Locks for Global, Database and Collection are handled by MongoDB while Document level locking is left to Storage Engine.