4

Currently I am trying to understand how to implement a CAS operation in mongodb properly to support optimistic locking. I've found out that updates in mongodb are atomic but I am not sure what this means (only the document rewrite is atomic or all cycle of update, including search for corresponding document and its rewriting, is atomic?). Lets consider following example.

  1. Some document exists in some collection with _id value set to 123 and has attribute cas_val set to 10.
  2. The first client wants to update cas_val of the document with _id equal to 123 to 11.
  3. The second client wants to update cas_val of the document with _id equal to 123 to 11.
  4. Both clients operate at the same time and operations can interleave.

So, is it possible that both operation succeed in case when no other updates to the document with _id 123 were performed?

P.S. Is there some build in technique in mongodb for the optimistic locking scenario?

4

2 回答 2

12

乐观锁定的正确技术是使用MongoDB 文档中详细描述的“如果当前更新” 。

这种技术的关键是更新条件不能简单地是{_id:123},而是必须是{_id:123, cas_val: 10},并且更新子句将 $set 适当的字段,包括将 cas_val 增加到 11。

现在,“输掉”比赛并第二次到达的线程将找不到要更新的匹配文档,并且需要通过重新获取文档(现在使用 cas_val 11)“重试”并再次尝试。确定更新是否成功的方法是检查 writeConcern 结构(它将指示“n”中有多少记录受到影响,以及“updatedExisting”字段中是否更新了现有记录)。

于 2013-05-13T17:30:50.290 回答
1

如果您使用具有正确运算符的原子更新,则无需获取文档然后对其进行更新,因此更新不会交错(至少数据集仍然是一致的)。顺便说一句,您似乎想要一个$inc操作员。

于 2013-05-13T13:56:49.090 回答