MongoDB c# driver using upsert with updateMany
16,753
Solution 1
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.
Solution 2
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...
}
Related videos on Youtube
Comments
-
asb almost 2 years
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.
-
eran otzap about 6 yearscould 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
-
reggaeguitar over 4 yearsWhat are filterExpression, updateValue and yourContext? updateBuilder isn't even used in your example also