asb
asb

Reputation: 833

MongoDB c# driver using upsert with updateMany

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.

Upvotes: 7

Views: 25346

Answers (4)

Tono Nam
Tono Nam

Reputation: 36058

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...
 }

Upvotes: 5

Hamid Karimi
Hamid Karimi

Reputation: 1

TModel is your model

var updateBuilder = new UpdateDefinitionBuilder<TModel>();
yourContext.UpdateMany(filterExpression, update.Set(updateExpression, updateValue));

Upvotes: -2

Sgedda
Sgedda

Reputation: 1531

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.

Upvotes: 4

Philip
Philip

Reputation: 3424

Upsert works fine when using updateMany aswell:

var options = new UpdateOptions { IsUpsert = true };
var result = await collection.UpdateManyAsync(filter, update, options);

Upvotes: 1

Related Questions