在MongoDB中,c#driver(2.0+)可以在执行和updateManyAsync时进行upsert吗? This示例有助于UpdateOne,但我正在寻找适用于updateMany的内容。
答案 0 :(得分:3)
Upsert工作正常:
var options = new UpdateOptions { IsUpsert = true };
var result = await collection.UpdateManyAsync(filter, update, options);
答案 1 :(得分:1)
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...
}
答案 2 :(得分:0)
这是在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,则会在找不到匹配项的情况下插入文档。
答案 3 :(得分:-1)
TModel是您的模型
var updateBuilder = new UpdateDefinitionBuilder<TModel>();
yourContext.UpdateMany(filterExpression, update.Set(updateExpression, updateValue));