MongoDB c# driver using upsert with updateMany
Asked Answered
M

4

7

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.

Make answered 27/11, 2015 at 23:40 Comment(0)
E
5
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...
 }
Elegist answered 28/9, 2019 at 3:26 Comment(0)
M
4

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.

Momism answered 15/2, 2019 at 8:28 Comment(0)
H
1

Upsert works fine when using updateMany aswell:

var options = new UpdateOptions { IsUpsert = true };
var result = await collection.UpdateManyAsync(filter, update, options);
Honor answered 14/12, 2015 at 21:53 Comment(1)
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. GOSchwing
C
-2

TModel is your model

var updateBuilder = new UpdateDefinitionBuilder<TModel>();
yourContext.UpdateMany(filterExpression, update.Set(updateExpression, updateValue));
Carpic answered 19/8, 2019 at 17:47 Comment(1)
What are filterExpression, updateValue and yourContext? updateBuilder isn't even used in your example alsoTiffie

© 2022 - 2024 — McMap. All rights reserved.