9

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?

i3arnon
  • 113,022
  • 33
  • 324
  • 344
coolblue2000
  • 3,796
  • 10
  • 41
  • 62

1 Answers1

8

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.

i3arnon
  • 113,022
  • 33
  • 324
  • 344