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...
 }
Share:
16,753

Related videos on Youtube

asb
Author by

asb

developer

Updated on June 04, 2022

Comments

  • asb
    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
    eran otzap about 6 years
    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
  • reggaeguitar
    reggaeguitar over 4 years
    What are filterExpression, updateValue and yourContext? updateBuilder isn't even used in your example also