使用.NET MongoDB API (MongoDB.Driver),建议实现乐观并发控制的方法是什么?例如,是否有类似于Server的ROWVERSION/时间戳的特性,例如,每当文档更改时自动更新的属性?还是有触发机制?或者其他机制?
发布于 2015-11-25 23:37:07
在MongoDB中,没有任何关于乐观并发的内置内容。如果你需要的话,你需要自己实现它。
您可以通过添加一个DateTime时间戳,在执行更新之前读取它,并使用该时间戳作为更新的筛选器来实现这一点。如果在您有机会更新之前更改了时间戳,则更新操作将无法找到文档。
例如:
UpdateResult updateResult;
do
{
var document = await collection.Find(_ => _.Id == id).SingleAsync(); // Get the current document
updateResult = await collection.UpdateOneAsync(_ => _.Id == id && _.TimeStamp == document.TimeStamp, Builders<Item>.Update...); // Update the document only if the timestamp is the same
} while (updateResult.ModifiedCount == 0); // Try until an update was successfullhttps://stackoverflow.com/questions/33928136
复制相似问题