MongoDb c# 2.0驱动AddToSet方法

本文关键字:AddToSet 方法 驱动 MongoDb | 更新日期: 2023-09-27 18:06:47

我有以下代码,这是用MongoDb 2.0 c#驱动程序实现的。但是我需要访问ProfileMailLists集合它将被插入。我已经在构造函数中使用p编写了预期的解决方案,但如何通过多个操作实现它?

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 });

MongoDb c# 2.0驱动AddToSet方法

我找到了以下解决方案:

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 });