mongodb - $set 仅当字段不存在时在 Mongodb 中使用数组运算符时
问题描述
我需要为我的文档设置一个默认值,但前提是该字段不存在。我的问题是我正在使用数组运算符。
我的要求是这样的:
db.myCollection.updateMany({}, { $set: { 'foo.$[].bar.$[].test': 42 }})
myCollection
包含以下两个文件:
{
foo: [
{ bar: [{ a: 1 }, { a: 2, test: 18 }] },
{ bar: [{ a: 1, test: 20 }, { a: 2, test: 18 }] }
]
}
{
foo: [
{ bar: [{ a: 1, test: 40 }, { a: 2, test: 18 }] },
{ bar: [{ a: 1, test: 20 }, { a: 2, test: 18 }] }
]
}
但如果该属性test
存在,我不想覆盖它。所以在我的例子中,我只想设置一个子元素的默认值(在第一个文档中)。
我怎样才能改变我的要求呢?
解决方案
您可以使用arrayFilters,
b
为bar
存在创建一个变量t
为test
不存在创建一个变量
db.myCollection.updateMany(
{},
{ $set: { 'foo.$[b].bar.$[t].test': 42 } },
{
arrayFilters: [
{ "b.bar": { $exists: true } },
{ "t.test": { $exists: false } }
]
}
)
推荐阅读
- java - 如何测量 Kotlin 协程中 aync 查询/请求的执行时间
- flutter - 开关按钮没有改变
- z3 - 如何在 Z3Py 中声明/使用数组和量词?
- amazon-web-services - 如何解决 msg us-west-1.signin.aws.amazon.com 发送无效响应。ERR_SSL_PROTOCOL_ERROR?
- docker - 使用 docker 和 nginx 在 localhost 中调试第三方身份验证
- javascript - 如何隐藏带有 cookie 的 div?
- reactjs - 来自 React 的自动化令牌未通过 Java Spring Boot 过滤器
- javascript - 将 HTML 标记替换为包含标记属性的字符串
- c# - 自定义模型绑定将子属性设置为 null
- javascript - 初始渲染后不会触发 useEffect