mongodb不同于其他关系型数据库,mongodb锁的粒度很大,2.2之前是整个server级别的锁,也叫全局锁,但是支持并发读,也就是说读可以同时读,但是只要有写操作,那么就加上锁,其他人既不能读也不能写,从2.2开始,这个锁的粒度缩小到了库级别,如果你有3个库,一个库有写锁,那么其他2个库还是继续可以读写操作,希望以后能像关系数据库一样到表级别。
2.2锁引发的条件:
Operation | Lock Type |
---|---|
Issue a query | Read lock |
Get more data from acursor | Read lock |
Insert data | Write lock |
Remove data | Write lock |
Update data | Write lock |
Map-reduce | Read lock and write lock, unless operations are specified as non-atomic. Portions of map-reduce jobs can run concurrently. |
Create an index | Building an index in the foreground, which is the default, locks the database for extended periods of time. |
db.eval() | Write lock or no lock. If this is used without thenolockoption, all JavaScript is blocked. |
aggregate() | Read lock |
The following administrative operations require an exclusive (i.e. write) lock to a the database for extended periods:
db.collection.ensureIndex(), when issuedwithoutsettingbackgroundtotrue,
reIndex,
compact,
db.repairDatabase(),
db.createCollection(), when creating a very large (i.e. many gigabytes) capped collection,
db.collection.validate(), and
db.copyDatabase(). This operation may lock all databases.
Thedb.collection.group()operation takes a read lock and does not allow any other threads to execute JavaScript while it is running.
The following administrative commands lock the database but only hold the lock for a very short time:
db.collection.dropIndex(),
db.collection.getLastError(),
db.isMaster(),
rs.status()(i.e.replSetGetStatus,)
db.serverStatus(),
db.auth(), and
db.addUser().
Does a read or write operation ever yield the lock?
New in version 2.0.
A read and write operations will yield their locks if themongodreceives apage faultorfetches data that is unlikely to be in memory. Yielding allows other operations that only need to access documents that are already in memory to complete whilemongodloads documents into memory.
Additionally, write operations that affect multiple documents (i.e.update()<db.collection.update()with themultiparameter,) will yield periodically to allow read operations during these log write operations. Similarly, long running read locks will yield periodically to ensure that write operations have the opportunity to complete.
Changed in version 2.2:The use of yielding expanded greatly in MongoDB 2.2. Including the “yield for page fault.” MongoDB tracks the contents of memory and predicts whether data is available before performing a read. If MongoDB predicts that the data is not in memory a read operation yields its lock while MongoDB loads the data to memory. Once data is available in memory, the read will reacquire the lock to completes the operation.
至于page fault,以及mmap请参阅http://docs.mongodb.org/manual/faq/storage/#faq-storage-page-faults