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

前端 未结 12 1684
死守一世寂寞
死守一世寂寞 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条回答
  •  梦毁少年i
    2020-12-24 12:37

    Answering my own question because I found a solution while doing research on the Internet.

    I think what I need to do is use an Optimistic Concurency Control.

    It consist in adding a timestamp, a hash or another unique identifier (I'll used UUIDs) to every documents. The unique identifier must be modified each time the document is modified. before updating the document I'll do something like this (in pseudo-code) :

    var oldUUID = doc.uuid;
    doc.uuid = new UUID();
    BeginTransaction();
    if (GetDocUUIDFromDatabase(doc.id) == oldUUID)
    {
       SaveToDatabase(doc);
       Commit();
    }
    else
    {
       // Document was modified in the DB since we read it. We can't save our changes.
       RollBack();
       throw new ConcurencyException();
    }
    

提交回复
热议问题