mongodb - MongoDB更新:-更新嵌套在数组中的多个对象(在多个文档中)
问题描述
我的收藏如下:
{
"_id" : "",
"team" : "avenger",
"persons" : [
{
"name" : "ABC",
"class" : "10",
"is_new" : true
},
{
"name" : "JHK",
"class" : "12",
"is_new" : true
},
{
"name" : "BNH",
"class" : "10",
"is_new" : true
}
]
},
{
"_id" : "",
"team" : "adrenaline",
"persons" : [
{
"name" : "HTU",
"class" : "11",
"is_new" : true
},
{
"name" : "NVG",
"class" : "10",
"is_new" : true
},
{
"name" : "SED",
"class" : "8",
"is_new" : true
}
]
}
我的目标是在“类”为“10”的“persons”中查找包含此类嵌套对象的所有此类文档,并将“is_new”字段更新为“false”
我正在使用“multi”设置为 true 的猫鼬更新
询问 :
{
persons: { $elemMatch: { class: "10" } }
}
选项:
{
multi : true
}
更新 :
我尝试过的第一个是:
{
$set : {
"persons.$.is_new" : false
}
}
第二个是:
{
$set : {
"persons.$[].is_new" : false
}
}
问题是:在更新操作中使用 $ 仅更新“persons”数组中所有匹配文档的第一个匹配项。
如果我使用$[],它会更新匹配文档中“persons”数组的所有对象。
解决方法可以是使用循环进行更新操作,但我认为这不应该是理想的情况。
我在文档中看不到任何内容,但发现有人报告此更新操作问题。
这不能使用单个查询来完成吗?循环浏览文档是我唯一的选择吗?
解决方案
您需要设置过滤的位置运算符$[<identifier>]
标识符
Model.update(
{ "persons": { "$elemMatch": { "class": "10" }}},
{ "$set" : { "persons.$[e].is_new" : false }},
{ "arrayFilters": [{ "e.class": "10" }], "multi" : true }
)
推荐阅读
- android - 将按钮更改为以编程方式舍入
- karate - 我也可以对 Json Api 请求使用以下相同的功能吗
- python - 如何在压缩和解压缩文件夹中搜索特定行
- c# - 是否可以将后代对象的集合作为 .NET Core 中的视图模型传入?
- json - 在python中更改json文件中的文本
- node.js - 通过电子邮件节点 js 和 Angular 5 进行帐户验证
- ios - UIGraphicsGetCurrentContext 的上下线颜色不正确
- java - 无法在 spring 2.0.3 中解析 @RestController 注释
- python - Python:匹配两个文件中的两列
- vba - 水平列表作为 Excel-VBA 表单 ComboBox 的 ControlSource