问题
I am trying to replace multiple occurrences of the same phrase in the same field.
Here is an example of the field 'imageUrl' contents:
"imageUrl" : "https://cdn.test.com/s/files/1/0035/4671/0061/products/Screen_Shot_2019-12-13_at_12.47.01_pm_2000x.png?v=1576212956\n \n https://cdn.test.com/s/files/1/0035/4671/0061/products/Screen_Shot_2019-12-13_at_12.47.01_pm_2000x.png?v=1576212956\n \n \n"
My current formula:
{
$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 } } ) )
Converts the following to:
"imageUrl" : "https://cdn.test.com/s/files/1/0035/4671/0061/products/Screen_Shot_2019-12-13_at_12.47.01_pm_850x.png?v=1576212956\n \n \n"```
However, im looking for the output to be:
"imageUrl" : "https://cdn.test.com/s/files/1/0035/4671/0061/products/Screen_Shot_2019-12-13_at_12.47.01_pm_850x.png?v=1576212956\n \n https://cdn.test.com/s/files/1/0035/4671/0061/products/Screen_Shot_2019-12-13_at_12.47.01_pm_850x.png?v=1576212956\n \n \n"
Both urls still present and adapted to the _850x
dimension.
Note: The field input may be more then one Url (could contain 2-7).
Thanks in advance for any assistance
回答1:
$reduce fits better for your use case:
Pseudocode
value = url.split("_2000x")[0]
for (item: url.split("_2000x")[1:])
value += "_850x" + item
db.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"
]
}
}
}
}
}
])
MongoPlayground
EDIT: To execute via Bash shell:
Windows:
create temp.js file with:
db.collection.aggregate(...).forEach(...)
create temp.bat file with:
@echo off
path/to/mongo.exe --uri put_here_mongodb+srv temp.js
Now run: temp.bat
Unix:
create temp.js file with:
db.collection.aggregate(...).forEach(...)
create temp.bat file with:
#!/bin/bash
path/to/mongo --uri put_here_mongodb+srv temp.js
Give execution permissions: chmod u+x temp.sh
Now run: ./temp.sh
来源:https://stackoverflow.com/questions/60385674/how-to-replace-multiple-occurrences-of-a-phrase-mongodb