I have (for example) 2 documents in db and 2 processes running in parallel
each process selects a single doc for update.
the select is done as a transaction.
in FindOneAndUpdateAsync the
filter filters documents with field named ‘locked’
and the update adds a field ‘locked’ to the doc
the first process (transaction) succeeds and the second fails with write violation.
for test purposes the transaction is never committed
public async Task<BsonDocument> GetNextAsyncTest(CancellationToken cancellationToken = default)
{
try
{
ClientSessionOptions sessionOptions = new ClientSessionOptions()
{
};
var session = await mongoCollection.Database.Client.StartSessionAsync(sessionOptions, cancellationToken);
session.StartTransaction();
FilterDefinition<BsonDocument> lockedNotExist = Builders<BsonDocument>.Filter.Exists("locked", false);
var filter = Builders<BsonDocument>.Filter.And(lockedNotExist);
var update = Builders<BsonDocument>.Update
.Set("locked", true);
var item = await mongoCollection.FindOneAndUpdateAsync<BsonDocument>(session, filter, update, default, cancellationToken);
if (item != null)
{
return item;
}
}
catch (Exception ex)
{
}
return null;
}