1

I’ve been reading the MongoDB documentation for hours, but I couldn’t find a clear and straightforward answer. When reading or writing a document in MongoDB, what type of lock (S, X, IS, IX) does it apply at the document-level ?

document

In the video I watched, it explains that an S lock is applied to the document during the reading process, and an X lock is applied during the writing process. Is this applicable in MongoDB as well?

video i watched

I have read various documents, but I couldn't find the information I'm looking for.

1 Answer 1

3

The direct answer is none.

When MongoDB writes a document, it will acquire IX locks on the database and the collection. If both of those are successful, it then sends the write operation to the underlying wiredTiger storage engine.

From the WiredTiger docs on Document Concurrency

WiredTiger uses document-level concurrency control for write operations. As a result, multiple clients can modify different documents of a collection at the same time.

For most read and write operations, WiredTiger uses optimistic concurrency control. WiredTiger uses only intent locks at the global, database and collection levels. When the storage engine detects conflicts between two operations, one will incur a write conflict causing MongoDB to transparently retry that operation.

Document updates are atomic, so there is no issue with reading - each read will retrieve either the document before the write, or after the entire write is applied, so the read lock is not necessary.

When several processes attempt updating a document at the same time, only one succeeds, the others incur a writeConflict, and are retried without notifying the client. The number of writeConflicts that have occured in the storage layer is reported by the serverStatus command.

1
  • Thank you so much <3
    – dragonborn
    Dec 22, 2023 at 10:09

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.