首页 > 解决方案 > 在 Mongo DB 中,如何更新可以为空的属性的嵌套属性

问题描述

我有一个带有一个settings字段的 MongoDB 文档,它本身带有两个嵌套字段,selectedSectionIds并且sectionColors. settings不是数组。我只需要更新该selectedSectionIds字段。

我的更新生成器如下所示:

  Builders<Account>.Update.Set(
    "settings.selectedSectionIds",
    sectionIds)

而且我打电话UpdateOneAsync没有什么特别的。

settings原始文档中不存在或已经包含某些内容时,一切正常,但是当settings为空时(它可以),我得到以下信息MongoWriteException

写入操作导致错误。不能使用部分(settings.selectedSectionIds的设置)遍历元素({settings: null})

如何更新我的构建器(或类映射/序列化器?)以支持所有场景?

(MongoDB C# 驱动程序 2.8)

标签: c#mongodb

解决方案


您不能更新 a 的属性null。如果它是一个空对象{},它将起作用。所以我的建议是通过 2 个步骤执行批量更新命令。在第一步中检查 null 并更改它,在第二步中根据需要设置子属性值。

为简洁起见,这是一个使用MongoDB.Entities的示例:

using MongoDB.Entities;

namespace StackOverflow
{
    public class Program
    {
        public class Account : Entity
        {
            public string Name { get; set; }
            public Settings Settings { get; set; }
        }

        public class Settings
        {
            public string[] SelectedSectionIDs { get; set; }
            public string[] SectionColors { get; set; }
        }

        private static void Main(string[] args)
        {
            new DB("test", "127.0.0.1");

            var acc1 = new Account
            {
                Name = "Account One",
                Settings = new Settings
                {
                    SectionColors = new[] { "green", "red" },
                    SelectedSectionIDs = new[] { "xxx", "yyy" }
                }
            }; acc1.Save();

            var acc2 = new Account
            {
                Name = "Account Two",
                Settings = null
            }; acc2.Save();

            DB.Update<Account>()

              .Match(a => a.Settings == null)
              .Modify(a => a.Settings, new Settings())
              .AddToQueue()

              .Match(_ => true)
              .Modify(a => a.Settings.SelectedSectionIDs, new[] { "aaa", "bbb" })
              .AddToQueue()

              .Execute();

        }
    }
}

推荐阅读