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?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With