MongoDb C # 2.0 AddToSet Utility

I have the following code which was implemented using MongoDb 2.0 c# driver

. But I need to access the collection MailLists

Profile

to be inserted. I wrote the expected solution using p

in the constructor, but how do I implement it with multiple operations?

IMongoCollection<Profile> dbCollection = DetermineCollectionName<Profile>();

var filter = Builders<Profile>.Filter.In(x => x.ID, profiles.Select(x => x.ID));

var updateMl = Builders<Profile>.Update.AddToSet(p => p.MailLists, new Profile2MailList
                        {
                            MailListId = maillistId,
                            Status = p.MailLists.MergeMailListStatuses(),
                            SubscriptionDate = DateTime.UtcNow
                        });

dbCollection.UpdateManyAsync(filter, updateMl, new UpdateOptions { IsUpsert = true });

      

+3


source to share


1 answer


I found the following solution:



IMongoCollection<Profile> dbCollection = DetermineCollectionName<Profile>();

var filter = Builders<Profile>.Filter.In(x => x.ID, profiles.Select(x => x.ID));

var profile2maillists = new List<Profile2MailList>();

foreach(var profile in profiles)
 {
     profile2maillists.Add(
         new Profile2MailList
                 {
                            MailListId = maillistId,
                            Status = profile.MailLists.MergeMailListStatuses(),
                            SubscriptionDate = DateTime.UtcNow
                 });
 }
var updateMl = Builders<Profile>.Update.AddToSetEach(p => p.MailLists, profile2maillists);
dbCollection.UpdateManyAsync(filter, updateMl, new UpdateOptions { IsUpsert = true });

      

+4


source







All Articles