Reputation: 516
What I want to do is the following after I receive a list of documents: 1) If Mongo has the unique reference for the document, replace the whole document with what I received 2) If Mongo doesn't have the unique reference, add new to the document.
What I think I have to do is something like this:
//Filter to identify if MongoDB already contains the document
var filter = Builders<MyClass>.Filter.In(x => x.Reference, documents.Result.Select(x => x.Reference));
//This is where I want to say delete and add new document but if it doesn't exist, add new
var update = Builders<MyClass>.Update.Set(x => x, documents.Result.Find(x));
await collection.UpdateManyAsync(filter,update);
Is there something built in to accomplish this task? I want to avoid comparing lists to figure out what to update and what to add new. I'm hoping Mongo has something built in.
Upvotes: 2
Views: 1742
Reputation: 890
You could pass in UpdateOptions with IsUpsert = true. This will tell MongoDB to insert a new document if one doesn't exist. Upsert is a portmanteau of update and insert.
await collection.UpdateManyAsync(filter,update, new UpdateOptions() {IsUpsert = true});
Upvotes: 1