Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Mongo update response says no document updated, but the document is there

I'm using MongoDb 2.6.10 and using C# Driver 1.9.2. The server has a replicaset of two servers.

My documents are of the format. itemId is unique.

{
    "itemID": 2314,
    "Favorites": [1, 24, 26, 34]
}

Then I have code to remove a favorite of the form

var query = Query.EQ("itemID", itemId);
var result = collection.Update(query, Update.Pull("Favorites", favoriteIdToRemove));

After each time, I check that result.DocumentsAffected is equal to 1. Once in a while, the value comes back as 0. When I go into MongoDB myself, I can find the document matching the itemID, and I can see the favoriteId that it tried to remove in the array is still there. result.OK is true, and there's no error information.

What could cause this to fail?

like image 985
Nikhil Avatar asked Jan 15 '16 20:01

Nikhil


1 Answers

I'm no expert but my guess is write concerns since there are different levels of guarantee for writing to and updating documents in MongoDB. See Write Concerns

So instead of using this method:

MongoCollection.Update Method (IMongoQuery, IMongoUpdate)

It might be better to use this method instead:

MongoCollection.Update Method (IMongoQuery, IMongoUpdate, WriteConcern)

And specify the WriteConcern to be

WriteConcern.WMajority

That way the update has the highest guarantee.

like image 130
Viider Storm Avatar answered Nov 15 '22 00:11

Viider Storm