If both two threads do read and write a same document:
try (ClientSession clientSession = client.startSession()) {
clientSession.startTransaction();
result = collection.find(clientSession, keyOfDoc);
if (result blah blah blah) {
// Change the doc
collection.insertOne(clientSession, doc);
}
clientSession.commitTransaction();
}
From the purpose of the transaction, one of the thread should get the edited version of another thread.
However, when both threads start transaction they both acquired a read lock, and then read the doc. Both the threads got the old version of the doc. and when they need to write the doc, they try to acquire write locks, which will make the transaction not atomic.
Another situation is the write-write conflict.
try (ClientSession clientSession = client.startSession()) {
clientSession.startTransaction();
collection.insertOne(clientSession, docDifferent);
collection.insertOne(clientSession, docSame);
clientSession.commitTransaction();
}
Both thread first acquires write locks of different documents, and then they acquire the write lock of the same document, as it is another transactional conflict.
What level of lock does MongoDB use? I know they use instance level before version 2.2 while transactions are supported since 4.0. If MongoDB doesn't use database level locks, How does MongoDB deal with transactional conflicts? Or if it uses database level locks, how does it deal with read-write conflicts?