Locking multi collection in Mongodb

Hi Team, We want to provide read and write lock on multi collections(more than 1 collection to be locked until db operation is completed) based on one field . for example we are updating CollectionA.fieldA at the same time we want to lock the document for fieldA in CollectionB so that until the operation in CollectionA is completed, user should not be able to operate query/insert/update/delete operations on CollectionB for the same document(fieldA).

I tried findOneAndUpdate() , but this works on a single document of one collection.

I also tried ACID operations for external commit, but locking is not happening for more than 1 collection and it is ending in auto commit for collection where we are trying to update, we don’t have any explicit control to include other collection into this locking scope.

Please let us know how to achieve this functionality.

Hello @Aman_Dillon ,

Welcome to the MongoDB Community! :wave:

I’d like to confirm my understanding of your goal. By locking based on field, do you mean that all the documents in the target collection having that field be locked, and documents without that field stay unlocked? That is, if field A exists in every document, the whole collection should be locked from any operation, and if field A exists in e.g. half of the documents, only those documents should be locked from any operation. Is my understanding here correct?

If my understanding is correct, currently MongoDB cannot lock multiple documents based on whether a field exists or does not exist. You can, however, lock a single document from writes using findOneAndUpdate as mentioned in this blog post.

Having said that, most database systems typically strive to allow maximum concurrency, which means: no read or write lock as much as possible, only lock as required, and typically allow reads as much as possible. Having a very strong read/write lock on possibly the whole collection/table runs counter to this goal, and I believe would not allow the system to scale. To achieve this goal, MongoDB uses intent locks, sessions, ACID multi-document transactions, read concerns, read preference and other methods to promote greater concurrency.

If you need further help, could you please explain your use case scenario in more details?

Regards,

Tarun Gaur

This topic was automatically closed 5 days after the last reply. New replies are no longer allowed.