使用 .NET MongoDB API (MongoDB.Driver),实现乐观并发控制的推荐方法是什么?例如,是否有任何类似于 SQL Server 的 ROWVERSION/TIMESTAMP 的东西,例如,每当文档更改时自动更新的属性?还是有触发机制?还是其他机制?
最佳答案
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 successfull
https://stackoverflow.com/questions/33928136/
相关文章:
mongodb - PyMongo:当 no_cursor_timeout=True 时光标会发生什
node.js - (mongoose/promises) 你如何检查文档是否是使用 findOne
mongodb - Mongodb聚合框架: what is the lock level of t
mongodb - WiredTiger - 辅助副本集成员重新同步期间的 “too many op
node.js - 如何在 MongoDB v3.0.5 中创建用户
mongodb - 无法使用 Sitecore 连接到 MongoDB
mysql - Waterline:在创建时填充模型相关对象(Sails)