收到文件 list 后,我要做的是: 1) 如果 Mongo 对文件有唯一的引用,用我收到的替换整个文件 2) 如果 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 有一些内置的东西。
最佳答案
您可以通过 IsUpsert = true 传入 UpdateOptions。如果文档不存在,这将告诉 MongoDB 插入一个新文档。更新插入是 portmanteau更新和插入。
await collection.UpdateManyAsync(filter,update, new UpdateOptions() {IsUpsert = true});
关于C# Mongo Driver 批量文件替换,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43812227/