Search code examples
mongodbmongodb-.net-drivermongodb-csharp-2.0

MongoDb C# Driver 2.0 add item to nested array


I have a Profiles document collection with array of the following documents :

public class Profile2MailList
{


    [BsonElement(elementName: "listId")]
    [BsonRequired]
    public int MailListId;

    [BsonElement(elementName: "status")]
    [BsonRequired]
    public int Status;

    [BsonElement(elementName: "subscriptionDate")]
    [BsonRequired]
    public DateTime SubscriptionDate;
} 

in each Profile. I need to add to the Profile2MailList array a new Profile2MailList document in each Profile based on Profile2MailList which already contains in a certain Profile. So i need to

  • Take needed profiles from Profiles collection
  • Update Profile2Maillist array in each Profile
  • Run update command How can i perform that action via C# 2.0 MongoDb Driver. I have MongoDb v 3.0.2. I try to make it by the following way :

       List<Profile> listProfiles = new List<Profile>();
                foreach (Profile item in profiles)
                {
                    item.MailLists.ToList().Add(new Profile2MailList(maillistId, item.MailLists.FirstOrDefault().Status));
                    var t = item;
                    listProfiles.Add(t);
                }
        dbCollection.UpdateManyAsync(listProfiles)
    

Solution

  • The method "UpdateManyAsync" only works if you want to perform one type of update, which doesn't seem to be your case. What you want to do is perform a Bulk-Update instead. Building on your example, you would want to do something like:

            var bulk = new List<WriteModel<Profile>>();
            foreach (Profile item in profiles)
            {
                var newProfile = new Profile2MailList(maillistId, item.MailLists.FirstOrDefault().Status);
                var filter = Builders<Profile>.Filter.Eq(g => g.Id, item.Id);
                var update = Builders<Profile>.Update.AddToSet(item.MailLists, newProfile);
                var updatemodel = new UpdateOneModel<Profile>(filter, update);
    
                bulk.Add(updatemodel);  
            }
            await profileCollection.BulkWriteAsync(bulk);
    

    The AddToSet operator adds a value to an array unless the value is already present.