It's not possible to lock a mongodb document. What if I need to?

前端 未结 12 1711
死守一世寂寞
死守一世寂寞 2020-12-24 11:34

I know that I can\'t lock a single mongodb document, in fact there is no way to lock a collection either.

However, I\'ve got this scenario, where I think I need some

12条回答
  •  情深已故
    2020-12-24 12:20

    Classic solution when you want to make something thread-safe is to use locks (mutexes). This is also called pessimistic locking as opposed to optimistic locking described here.

    There are scenarios when pessimistic locking is more efficient (more details here). It is also far easier to implement (major difficulty of optimistic locking is recovery from collision).

    MongoDB does not provide mechanism for a lock. But this can be easily implemented at application level (i.e. in your code):

    1. Acquire lock
    2. Read document
    3. Modify document
    4. Write document
    5. Release lock

    The granularity of the lock can be different: global, collection-specific, record/document-specific. The more specific the lock the less its performance penalty.

提交回复
热议问题