我不认为这可以在简单的更新查询中完成,尤其是如果您想替换字段中的子字符串。
使用(更新)聚合查询时,您需要:
-
$map
-迭代
videos
大堆覆盖的匹配元素
resolutions
大堆
-
$map
-迭代
决议
数组,并更新
file_url
通过替换匹配的子字符串来替换文档的字段(
$replaceOne
或
$replaceAll
)如果该值满足正则表达式(
$regexMatch
).否则,保持为原始值。
db.getCollection('projects').update({
"videos.resolutions.file_url": {
$regex: oldUrl
},
"videos.converted": true
},
[
{
$set: {
videos: {
$map: {
input: "$videos",
as: "video",
in: {
$cond: {
if: {
$eq: [
"$video.converted",
true
]
},
then: {
$mergeObjects: [
"$$video",
{
resolutions: {
$map: {
input: "$$video.resolutions",
as: "resolution",
in: {
$cond: {
if: {
$regexMatch: {
input: "$$resolution.file_url",
regex: oldUrl
}
},
then: {
$mergeObjects: [
"$$resolution",
{
file_url: {
$replaceAll: {
input: "$$resolution.file_url",
find: oldUrl,
replacement: newUrl
}
}
}
]
},
else: "$$resolution"
}
}
}
}
}
]
},
else: "$$video"
}
}
}
}
}
}
])
Demo @ Mongo Playground