Lock a collection while a transaction is active

Hello,

I need to lock the entire collection when a specific transaction is opened.

My use case is the following:
I have a backend software in Kotlin which declare some endpoint to modify some object on database.

In a scheduled task, i run a “cleaning operation”, i read all the documents, modify it, removing some informations and storing these informations in another collection. Then i save the “clean” documents again on database.
All this operation is in a single transaction. It can require some seconds or tens of seconds, based on amount of documents.

While i execute this operation i need that any other read or write on the database returns error (or wait until the transaction is closed).
If a document is read, is not updated, and if modified and saved after the transaction end, i will overwrite the modify done by the transaction.
So i need to lock both read and write.

I’ve done this test:

  • The Scheduled task starts. Start the transaction. Read all the documents to clean.
  • Now, with a REST API i modify one of this document. The document is read and modified. I tried to read it again after the save, and the modification is effectively done.
  • Now the transaction modify that document again, ignoring the modification done by the user via REST API

I have no writeConflict, both operations modify the same document, but the first is overridden by the second.

I search various topic on this argument but i found no way in MongoDB to lock the entire collection while i run my transaction.

I cannot use a findAndModify because, after i read the document, i need to extract informations on it, read them, save in another collection, remove them, adding e reference to the new document in the other collection and finally update the document.

I use Spring data for MongoDB.

org.springframework.data:spring-data-mongodb:3.4.2
org.mongodb:mongodb-driver-sync:4.6.1

My read and write concern configuration is the default:

defaultReadConcern: { level: 'local' },
defaultWriteConcern: { w: 'majority', wtimeout: 0 },

Thanks in advice in someone can help me.