mongodb - 使用匹配元素更新子子文档的数组
问题描述
以下是我的架构:
{
"_id":ObjectId("5c49c783de72ec2ec47b95d1"),
"placement":[
{
"offer":[
{
"sent_by":"John",
"comment":""
},
{
"sent_by":"Mary",
"comment":""
}
]
}
]
}
我想更新placement.offer.comment
where placement.offer.sent_by
isMary
但它总是更新第一条记录。我不想提供像placement.0.offer.1.sent_by
.
这应该是生成的文档:
{
"_id":ObjectId("5c49c783de72ec2ec47b95d1"),
"placement":[
{
"offer":[
{
"sent_by":"John",
"comment":""
},
{
"sent_by":"Mary",
"comment":"Some comment updated"
}
]
}
]
}
解决方案
您需要使用数组过滤器来实现:
db.collection.update(
{ /* add additional query filters here */ },
{ $set: { "placement.$[].offer.$[o].comment": "Some updated comment" } },
{ arrayFilters: [ { "o.sent_by": "Mary" } ] }
)
推荐阅读
- javascript - 如何根据文本框中的值填充下拉列表?
- c# - 如何使用 ASP.NET MVC 剃须刀中的实体框架检查数据库中是否存在记录?
- python - 将 Matlab 文件加载到 python 时出现关键错误
- javascript - JavaScript 内存泄漏导致页面无法加载?
- android - 如何在 Android Q 中拍照并保存?
- javascript - jQuery 日期选择器设置日期无法正常工作
- python - 用字母替换数字
- powershell - 在给定进程 ID 的情况下终止 PowerShell 中的进程树
- javascript - 将自动高度设置为具有最内层绝对 div 的父 div
- c# - 如何将旧 Excel 文件中的多张工作表中的数据导出到新 Excel 文件中的一张工作表中