簡體   English   中英

MongoDB c# 驅動程序使用 upsert 和 updateMany

[英]MongoDB c# driver using upsert with updateMany

在 MongoDB c# 驅動程序 (2.0+) 中,我們可以在執行和 updateManyAsync 時執行更新插入嗎? 示例對 UpdateOne 有所幫助,但我正在尋找適用於 updateMany 的內容。

使用updateMany時,Upsert工作正常:

var options = new UpdateOptions { IsUpsert = true };
var result = await collection.UpdateManyAsync(filter, update, options);
UpdateDefinition<Phone> updateDefinition = Builders<Phone>.Update.Set(x => x.Name, "Updated Name");
MongoDb.GetCollection<Phone>("Phone").UpdateOne(x => x._id == "foo", updateDefinition); // replaces first match
MongoDb.GetCollection<Phone>("Phone").UpdateMany(x => x.SomeProp == 5, updateDefinition); // replaces all matches

假設你有一個類:

class Phone
{
    public string _id {get; set;} // this is the primary key because Mongo uses _id as primary key
    public string Name {get;set;}
    public int SomeProp {get;set;}

    // etc...
 }

以下是在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,則在未找到匹配項時將插入文檔。

TModel是您的模型

var updateBuilder = new UpdateDefinitionBuilder<TModel>();
yourContext.UpdateMany(filterExpression, update.Set(updateExpression, updateValue));

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM