c# - 在 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)
解决方案
您不能更新 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();
}
}
}
推荐阅读
- javascript - 类参数的继承
- java - Dijkstra算法在大图中找到两个节点之间的最短路径?
- mysql - 如何在mysql中将utf-8 hex转换为带有caron的字母?
- python - 请求HTML为 text/html
- javascript - 使用 cssText 切换元素
- apache - Shiro Annotation 不适用于带有 Jersey REST 和 JDBC Realm 的 Spring Boot 2.0.4
- javascript - node-api 内的 SQlite 池连接
- javascript - 如果仅存在 1 个管理员而不显示对话框,则删除按钮会刷新页面。我错过了什么?
- json - 如何在服务器端接收带有音频文件和文件信息的 Json 对象(Spring 启动控制器)
- python-2.7 - 如何将 SVM 类概率转换为 logits?