Alessandro Di Lello
Alessandro Di Lello

Reputation: 1211

MongoDB C# Driver 2.0 - Update document

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

Upvotes: 45

Views: 69633

Answers (4)

Hesam Mahmoodi
Hesam Mahmoodi

Reputation: 43

use ObjectId.Parse(id)

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

Upvotes: 1

reda bakr
reda bakr

Reputation: 119

you can use LINQ as following:

await context.collection.ReplaceOneAsync(b=> b.Id == item.Id,item);

Upvotes: 8

i3arnon
i3arnon

Reputation: 116636

To add to mnemosyn's answer, while a simple ReplaceOneAsync does update a document it isn't equivalent to Save as Save would also insert the document if it didn't find one to update.

To achieve the same behavior with ReplaceOneAsync you need to use the options parameter:

MyType myObject; 
var result = await collection.ReplaceOneAsync(
    item => item.Id == id, 
    myObject, 
    new UpdateOptions {IsUpsert = true});

Upvotes: 33

mnemosyn
mnemosyn

Reputation: 46331

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)

Upvotes: 49

Related Questions