我试图在同一个字段中替换同一短语的多次出现。
下面是字段“imageUrl”内容的一个示例:
"imageUrl“:"2000x.png?v=1576212956\n \n 2000x.png?v=1576212956\n \n”
我目前的公式:
{
$match: {
imageUrl: { $regex: "_2000x" },
brand: "Goat The Label"
}
},
{
$addFields: {
imageUrl: { $split: [ "$imageUrl", "_2000x" ] }
}
},
{
$addFields: {
imageUrl: {
$concat: [
{ $arrayElemAt: [ "$imageUrl", 0 ] },
"_850x",
{ $arrayElemAt: [ "$imageUrl", 1 ] }
]
}
}
}]).forEach( doc => db.product.updateOne( { _id: doc._id }, { $set: { imageUrl: doc.imageUrl } } ) )将下列内容转换为:
"imageUrl“:"850x.png?v=1576212956\n \n \n”‘’
然而,我希望输出是:
"imageUrl“:"850x.png?v=1576212956\n \n 850x.png?v=1576212956\n \n”
这两个urls仍然存在并适应于_850x维度。
注:字段输入可能超过一个(可能包含2-7)。
预先感谢您的帮助
发布于 2020-02-25 01:34:38
$reduce更适合您的用例:
伪码
value = url.split("_2000x")[0]
for (item: url.split("_2000x")[1:])
value += "_850x" + itemdb.collection.aggregate([
{
$match: {
imageUrl: {
$regex: "_2000x"
},
brand: "Goat The Label"
}
},
{
$addFields: {
imageUrl: {
$reduce: {
input: {
$slice: [
{
$split: [
"$imageUrl",
"_2000x"
]
},
1,
{
$size: {
$split: [
"$imageUrl",
"_2000x"
]
}
}
]
},
initialValue: {
$arrayElemAt: [
{
$split: [
"$imageUrl",
"_2000x"
]
},
0
]
},
in: {
$concat: [
"$$value",
"_850x",
"$$this"
]
}
}
}
}
}
])编辑:通过Bash执行的:
窗口:
使用以下内容创建temp.js文件:
db.collection.aggregate(...).forEach(...)使用以下内容创建temp.bat文件:
@echo off
path/to/mongo.exe --uri put_here_mongodb+srv temp.js现在运行:temp.bat
Unix:
使用以下内容创建temp.js文件:
db.collection.aggregate(...).forEach(...)使用以下内容创建temp.bat文件:
#!/bin/bash
path/to/mongo --uri put_here_mongodb+srv temp.js授予执行权限:chmod u+x temp.sh
现在运行:./temp.sh
https://stackoverflow.com/questions/60385674
复制相似问题