MongoDB Optimistic Concurrency Control With .NET

爱⌒轻易说出口 提交于 2019-12-09 17:43:00

问题


Using the .NET MongoDB API (MongoDB.Driver), what is the recommended approach for implementing optimistic concurrency control? For example, is there anything analogous to SQL Server's ROWVERSION/TIMESTAMP, e.g., a property that is automatically updated whenever the document changes? Or is there a trigger mechanism? Or any other mechanism?


回答1:


There isn't anything built-in regarding optimistic concurrency in MongoDB. You need to implement that yourself if you need it.

You can do that by adding a DateTime timestamp, reading it before performing an update and using that timestamp as the filter for update. If the timestamp was changed before you had a chance to update than the update operation won't be able to find the document.

For example:

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-optimistic-concurrency-control-with-net

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!