MongoDB Clarifications – Common Questions and Answers on MongoDB

mongodb

I have a few questions, hoping I can get answers.

  1. what does it mean when the Mongodb said:

    Clients can read documents while write operations are in progress

    I can see partially updated document? or the document will be under lock and no one can see it until the lock yielded?

  2. I need to know if two operation can update the same document with WiredTiger or MMAP V1? if so, what about reading at the same time of write or update?
  3. If I use $isolate is this enough to be sure that no one could write on the same document?

Best Answer

The locking of documents differs between the WiredTiger and the MMAPv1 storage engine. When using the Wired Tiger storage engine, write operations only hold an exclusive lock at document level. This means that multiple threads can update multiple documents in the same collection at the same time, however, they can NOT update the same document at the same time. In addition to an exclusive lock at document level, WiredTigger also holds intent locks at the global, database and collection levels. These intent locks will not block reading or writing operations,however, when the storage engine detects conflicts between two operations, one will incur a write conflict causing MongoDB to transparently retry that operation.

When using the classical 'MMAPv1` storage engine, a write operation hold an exclusive lock on the entire collection and therefore multiple threads can NOT write to the same collection at the same time, let alone write to the same document at the same time.

The locking does not occur when reading from a document, so two threads can a document at the same time. Regarding $isolated, you need to use this for write operations that affect multiple documents. Setting this flag prevents a write operation from yielding to other reads and writes once the first document is written. For example, if you are running an update query on document 1,2,...100, setting the $isolated flag will prevent document 100 being changed while the update query is updating document 1.