我正在尝试在 mongoDB 中使用 mongosh 替换我在集合中为其他人选择的所有单词。
例如,我有这个:
_id:12345678901
name:"Peter Parker"
profession:"Superhero"
_id:12345678902
name:"Peter Parker"
profession:"Journalist"
_id:12345678902
name:"Hulk"
profession:"Software Developer"
我想用“Superman”替换名为“firstList”的集合中的所有“Peter Parker”以获得以下结果:
_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")"
}
})
最佳答案
根据您的数据,您不需要正则表达式
,您可以按原样使用该单词进入查找阶段。
您可以使用 []
将聚合查询用于更新,如下所示:
db.collection.update({
"name": {
"$regex": "Peter Parker"
}
},
[
{
"$set": {
"name": {
"$replaceAll": {
"input": "$name",
"find": "Peter Parker",
"replacement": "Superman"
}
}
}
}
],
{
"multi": true
})
示例 here
顺便说一句,如果需要,您可以将正则表达式用于 find
对象。但如果您想匹配整个单词“Peter Parker”,您可以不使用正则表达式来使用。
关于javascript - 使用 REGEX 替换 mongoDB 中所有相同的单词,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/69191753/