Locking in MongoDB
Document-level and collection-level locking is mentioned throughout this chapter and also in several other chapters in this book. It is important to understand how locking works and why it is important.
Database systems use the concept of locks to achieve ACID properties. When there are multiple read or write requests coming in parallel, we need to lock our data so that all the readers and writers have consistent and predictable results.
MongoDB uses multi-granularity locking. The available granularity levels, in descending order, are as follows:
- Global
- Database
- Collection
- Document
The locks that MongoDB and other databases use are as follows, in order of granularity:
- IS: Intent shared
- IX: Intent exclusive
- S: Shared
- X: Exclusive
If we use locking at a granularity level with S or X locks, then all the higher levels need to be locked with an intent lock of the same type.
Other rules for locks are as...