2017-05-05 74 views
0

我收到文檔列表後,我想要做的事情如下: 1)如果Mongo具有文檔的唯一引用,則用接收的內容替換整個文檔 2)如果Mongo沒有獨特的參考,爲文檔添加新的內容。C#Mongo驅動程序批量文檔替換

我想我需要做的就是這樣的事情:

//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); 

有內置來完成這個任務的東西嗎?我想避免比較列表以找出要更新的內容以及要添加的內容。我希望Mongo有內置的東西。

回答

0

你可以在UpdateUpptions中傳入IsUpsert = true。這將告訴MongoDB在不存在的情況下插入一個新的文檔。 Upsert是更新並插入的portmanteau

await collection.UpdateManyAsync(filter,update, new UpdateOptions() {IsUpsert = true}); 
相關問題