使用updateMany的upsert的MongoDB c#驱动程序

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了使用updateMany的upsert的MongoDB c#驱动程序相关的知识,希望对你有一定的参考价值。

在MongoDB c#driver(2.0+)中我们可以在执行和updateManyAsync时进行upsert吗? This示例有助于UpdateOne,但我正在寻找适用于updateMany的东西。

答案

使用updateMany时,Upsert工作正常:

var options = new UpdateOptions { IsUpsert = true };
var result = await collection.UpdateManyAsync(filter, update, options);
另一答案

以下是在C#.Net核心中使用UpdateMany的更完整示例:

BostadsUppgifterMongoDbContext context = new BostadsUppgifterMongoDbContext(_configuration.GetConnectionString("DefaultConnection"), _configuration["ConnectionStrings:DefaultConnectionName"]);
var residenceCollection = context.MongoDatabase.GetCollection<Residence>("Residences");
residenceCollection.UpdateMany(x =>
    x.City == "Stockholm",
    Builders<Residence>.Update.Set(p => p.Municipality, "Stoholms län"),
    new UpdateOptions { IsUpsert = false }
);

如果IsUpsert设置为true,则在未找到匹配项时将插入文档。

以上是关于使用updateMany的upsert的MongoDB c#驱动程序的主要内容,如果未能解决你的问题,请参考以下文章

在 mongo 和 upsert 中更新数组

学习mongo系列修改器($inc/$set/$unset/$push/$pop/upsert)

Spring Boot Mongo Upsert 数组中的元素

《MongoDB入门教程》第20篇 文档更新之UPSERT

《MongoDB入门教程》第20篇 文档更新之UPSERT

updateMany() 后如何获取所有更新文档的值?