您可以像这样利用批量写入功能:
var list = new[] {
new Book { Id = "1", UniqueId = "100", Title = "one" }, //existing record
new Book { Id = "2", UniqueId = "200", Title = "two" },
new Book { Id = "3", UniqueId = "300", Title = "three" }
};
var models = new List<WriteModel<Book>>(list.Length);
foreach (var book in list)
{
var upsert = new ReplaceOneModel<Book>(
filter: Builders<Book>.Filter.Eq(e => e.UniqueId, book.UniqueId),
replacement: book)
{ IsUpsert = true };
models.Add(upsert);
}
var result = await collection.BulkWriteAsync(models);
var addedIds = result.Upserts.Select(u => u.Id.AsString);
var replacedIds = list.Select(x => x.Id).Except(addedIds);
Console.WriteLine("added ids: " + string.Join(",", addedIds));
Console.WriteLine("duplicate ids: " + string.Join(",", replacedIds));
Console.ReadLine();
请记住,如果任何属性/字段已更改,这实际上将替换现有记录。如果实体中的数据与数据库中的文档完全相同,则将被忽略。