使用正则表达式替换 mongoDB 中所有相同的词
Replace all the same words in mongoDB using REGEX
我正在尝试 mongoDB 使用 mongosh 替换我 select 在其他人的集合中的所有单词。
例如,我有这个:
_id:12345678901
name:"Peter Parker"
profession:"Superhero"
_id:12345678902
name:"Peter Parker"
profession:"Journalist"
_id:12345678902
name:"Hulk"
profession:"Software Developer"
我想将名为“firstList”的集合中的所有“Peter Parker”替换为“Superman”以获得此:
_id:12345678901
name:"Superman"
profession:"Superhero"
_id:12345678902
name:"Superman"
profession:"Journalist"
_id:12345678902
name:"Hulk"
profession:"Software Developer"
我正在尝试这个,但它不起作用:
db.firstList.replace({
"name": {
"$regex": "(/( |^)Peter Parker\b/g, "$Superman")"
}
})
根据你的数据,你不需要regex
,你可以直接使用word into find stage。
您可以像这样使用 []
使用聚合查询进行更新:
db.collection.update({
"name": {
"$regex": "Peter Parker"
}
},
[
{
"$set": {
"name": {
"$replaceAll": {
"input": "$name",
"find": "Peter Parker",
"replacement": "Superman"
}
}
}
}
],
{
"multi": true
})
示例here
顺便说一下,如果需要,您可以将正则表达式用于 find
对象。但是如果你想匹配整个单词“Peter Parker”,你可以不使用正则表达式。
我正在尝试 mongoDB 使用 mongosh 替换我 select 在其他人的集合中的所有单词。
例如,我有这个:
_id:12345678901
name:"Peter Parker"
profession:"Superhero"
_id:12345678902
name:"Peter Parker"
profession:"Journalist"
_id:12345678902
name:"Hulk"
profession:"Software Developer"
我想将名为“firstList”的集合中的所有“Peter Parker”替换为“Superman”以获得此:
_id:12345678901
name:"Superman"
profession:"Superhero"
_id:12345678902
name:"Superman"
profession:"Journalist"
_id:12345678902
name:"Hulk"
profession:"Software Developer"
我正在尝试这个,但它不起作用:
db.firstList.replace({
"name": {
"$regex": "(/( |^)Peter Parker\b/g, "$Superman")"
}
})
根据你的数据,你不需要regex
,你可以直接使用word into find stage。
您可以像这样使用 []
使用聚合查询进行更新:
db.collection.update({
"name": {
"$regex": "Peter Parker"
}
},
[
{
"$set": {
"name": {
"$replaceAll": {
"input": "$name",
"find": "Peter Parker",
"replacement": "Superman"
}
}
}
}
],
{
"multi": true
})
示例here
顺便说一下,如果需要,您可以将正则表达式用于 find
对象。但是如果你想匹配整个单词“Peter Parker”,你可以不使用正则表达式。