In MongoDB c# driver (2.0+) can we do an upsert when doing and updateManyAsync? This example helps with UpdateOne, but i am looking for something that works with updateMany.
MongoDB c# driver using upsert with updateMany
Asked Answered
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
Assuming you have a class:
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...
}
Here is a more complete example of using UpdateMany in C# .Net core:
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 }
);
If IsUpsert
is set to true it will insert a document if no match was found.
Upsert works fine when using updateMany aswell:
var options = new UpdateOptions { IsUpsert = true };
var result = await collection.UpdateManyAsync(filter, update, options);
could you please explain filter and update. And by explain i mean words + example lets say i have a model person and i would like to upsert many people. they are are unique by id. GO –
Schwing
TModel is your model
var updateBuilder = new UpdateDefinitionBuilder<TModel>();
yourContext.UpdateMany(filterExpression, update.Set(updateExpression, updateValue));
What are filterExpression, updateValue and yourContext? updateBuilder isn't even used in your example also –
Tiffie
© 2022 - 2024 — McMap. All rights reserved.