我有一个Profiles
文档集合,其中包含以下文档数组:
public class Profile2MailList
{
[BsonElement(elementName: "listId")]
[BsonRequired]
public int MailListId;
[BsonElement(elementName: "status")]
[BsonRequired]
public int Status;
[BsonElement(elementName: "subscriptionDate")]
[BsonRequired]
public DateTime SubscriptionDate;
}
每个Profile
中的。
我需要在Profile2MailList
数组中添加基于Profile2MailList
的{{1}}个新文档,该文档已包含在某个Profile
中。所以我需要
Profile2MailList
集合Profile
Profiles
个数组
运行更新命令
我如何通过Profile2Maillist
执行该操作。我有Profile
。
我尝试通过以下方式制作它:
C# 2.0 MongoDb Driver
答案 0 :(得分:3)
方法“UpdateManyAsync”仅在您要执行一种类型的更新时才有效,这似乎不是您的情况。您要做的是执行批量更新。根据您的示例,您可能希望执行以下操作:
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);
AddToSet运算符向数组添加值,除非该值已存在。