MongoDB C# Driver 2.0 - Update document

Alessandro Di Lello picture Alessandro Di Lello · May 15, 2015 · Viewed 45.6k times · Source

I'm currently upgrading my code to MongoDB C# driver 2.0 and I'm having issues upgrading the code to update documents.

using the old version I was able to do something like this:

MyType myObject; // passed in 
var collection = _database.GetCollection<MyType>("myTypes");
var result = collection.Save(myObject);

I'm struggling to find a way to do this in the new version. I have found a few examples of updating single fields like

var filter = Builders<MyType>.Filter.Eq(s => s.Id, id);
var update = Builders<MyType>.Update.Set(s => s.Description, description);
var result = await collection.UpdateOneAsync(filter, update);

I'd like to update all the fields as I was doing in the old version with the method Save.

Any ideas ?

Thanks a lot

Answer

mnemosyn picture mnemosyn · May 15, 2015

I think you're looking for ReplaceOneAsync():

MyType myObject; // passed in 
var filter = Builders<MyType>.Filter.Eq(s => s.Id, id);
var result = await collection.ReplaceOneAsync(filter, myObject)