MongoDB c# driver using upsert with updateMany

asb picture asb · Nov 28, 2015 · Viewed 14.1k times · Source

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.

Answer

Sgedda picture Sgedda · Feb 15, 2019

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.