我想在 Mongo 中进行批量更新插入。基本上我从供应商那里得到了一个对象列表,但我不知道哪些是我之前得到的(并且需要更新),哪些是新的。我可以一一进行更新插入,但 UpdateMany 不适用于更新插入选项。
因此,我采取了选择文档、用 C# 进行更新并进行批量插入的方法。
public async Task BulkUpsertData(List<MyObject> newUpsertDatas)
{
var usernames = newUpsertDatas.Select(p => p.Username);
var filter = Builders<MyObject>.Filter.In(p => p.Username, usernames);
//Find all records that are in the list of newUpsertDatas (these need to be updated)
var collection = Db.GetCollection<MyObject>("MyCollection");
var existingDatas = await collection.Find(filter).ToListAsync();
//loop through all of the new data,
foreach (var newUpsertData in newUpsertDatas)
{
//and find the matching existing data
var existingData = existingDatas.FirstOrDefault(p => p.Id == newUpsertData.Id);
//If there …Run Code Online (Sandbox Code Playgroud)