【问题标题】:MongoDb C# Driver 2.0 add item to nested arrayMongoDb C# Driver 2.0 将项目添加到嵌套数组
【发布时间】:2015-09-18 09:58:23
【问题描述】:

我有一个 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。 我需要在每个Profile 中向Profile2MailList 数组添加一个新的Profile2MailList 文档,该文档基于Profile2MailList,它已经包含在某个Profile 中。所以我需要

  • Profiles 集合中获取所需的配置文件
  • 更新 Profile2Maillist 数组中的每个 Profile
  • 运行更新命令 我如何通过C# 2.0 MongoDb Driver 执行该操作。我有MongoDb v 3.0.2。 我尝试通过以下方式实现:

       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)
    

【问题讨论】:

  • 我知道新 C# 驱动程序中的更改记录不充分,但您至少必须尝试过一些东西。请展示您对此的尝试(即使它失败),因为没有它,这看起来就像一个“为我编写代码”的问题。尝试和失败是可以接受的,它至少清楚地表明了你想要做什么。
  • @BlakesSeven 我不知道该怎么做,我可以使用InsertManyAsync 以防我需要插入新文档 - 它工作正常,但是如何更新许多复杂的文档更新场景?我能够执行 UpdateOneAsyncUpdateDefinition 不能满足我的需求
  • 非常大的edit 链接您的问题。显示您失败的尝试。相信没有人会笑。但任何努力都得不到我的帮助。
  • @BlakesSeven 我添加了其他信息

标签: mongodb mongodb-.net-driver mongodb-csharp-2.0


【解决方案1】:

“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 运算符将一个值添加到数组中,除非该值已经存在。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-07-02
    • 2021-11-04
    • 2020-07-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多