Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

New alternative for old .net Driver MongoCollection.Save?

I have some C# code which uses the old 1.x version of MongoDB driver which offers a generic save method using the MongoCollection.Save() method. However after upgrading to 2.0 this method appears to be gone and replaced with an Update method which requires all the updated fields on the object to be specified (which is obviously no good for a generic method...)

How do I keep the functionality of the old Save method (ie just pass in an object to update all fields) in the 2.0 driver?

like image 937
coolblue2000 Avatar asked May 21 '15 22:05

coolblue2000


1 Answers

You can use ReplaceOneAsync with the IsUpsert flag and an id query:

public async Task<ReplaceOneResult> Save(Hamster hamster)
{
    var replaceOneResult = await collection.ReplaceOneAsync(
        doc => doc.Id == hamster.Id, 
        hamster, 
        new UpdateOptions {IsUpsert = true});
    return replaceOneResult;
}

You can look at ReplaceOneResult.MatchedCount to see whether it was an insert or update.

like image 151
i3arnon Avatar answered Nov 15 '22 16:11

i3arnon