I'm experiencing some strange behavior using the C# driver for MongoDB. I'm attempting to perform an update that replaces multiple fields, so I'm using the ReplaceOneAsync()
method from the API. My connections to any collection is made with WriteConcern.Acknowledged
so I can handle cases where the database fails to be updated for whatever reason (like in this situation).
Sometimes the database will not update a record, but I cannot determine why. When attempting to debug this case I am looking at the ReplaceOneResult
object returned from the ReplaceOneAsync method and it shows that MatchedCount = 1, but the ModifiedCount = 0 as seen in the screenshot below from my debugger:
How is this possible? If it matched the one id that I'm trying to replace, why wouldn't it perform the modification? Does this mean there is some sort of error state occurring causing it to fail silently? It doesn't throw any exceptions so if this is the case how can I determine what's going wrong?
Here's the simple update method:
public virtual async Task<bool> Update(T entity)
{
if (entity.Id == ObjectId.Empty)
throw new ArgumentException("Id must be available and in the database to perform an update.");
ReplaceOneResult result = await this.MongoConnectionHandler.MongoCollection.ReplaceOneAsync(e => e.Id == entity.Id, entity);
return result.ModifiedCount > 0;
}
You can replace a single document using the collection. replaceOne() method. replaceOne() accepts a query document and a replacement document. If the query matches a document in the collection, it replaces the first document that matches the query with the provided replacement document.
replaceOne() replaces the first matching document in the collection that matches the filter , using the replacement document.
If the MatchedCount = 1 and ModifiedCount = 0 it should be because your replacement document is identical to the existing document.
So they matched, but no replacement was necessary because they were identical.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With