Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ReplaceOne Method's Filter Matches Document, Does Not Perform Replacement

Tags:

c#

mongodb

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:

Debugging Screenshot

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;
}
like image 887
JNYRanger Avatar asked Sep 17 '15 14:09

JNYRanger


People also ask

How do I replace a document in Mongodb?

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.

Which method replaces a single document within the collection based on the filter?

replaceOne() replaces the first matching document in the collection that matches the filter , using the replacement document.


1 Answers

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.

like image 127
Robert Stam Avatar answered Oct 13 '22 11:10

Robert Stam