replace Regex with $replaceAll mongodb



我正在尝试替换字段中所有不必要的文本

例如:

_id:12345678901,
name:"Company Z"
_id:12345678902,
name: "Corp Y"
_id:12345678902,
name: "Corporation X"

我想在name字段中删除Corp,CorporationCompany,并为其创建一个新字段,但我不能使用regex

目标:

_id:12345678901,
name: "Company Z",
newName: "Z"
_id:12345678902,
name: "Corp Y",
newName: "Y"
_id:12345678902,
name: "Corporation X",
newName: "X"

目前我有这个:


db.customers.updateMany(
{  },
[{
$set: { newName: {
$replaceAll: { input: "$name", find: {"$regexFind": { input: "$name", regex: '/(Corp)|(Corporation)|(Company)/gi' } }, replacement: "" }
}}
}]
)

但它似乎不起作用。

BTW我使用mongod 4.4.14

问题是$regexFind不返回字符串,而是对象文档首先,您必须执行$regexFind,然后使用返回的对象匹配字段来执行$replaceAll。下面是一个示例聚合管道,它将对象转换为所需的对象:

{
$addFields: {
"regexResObject": {
"$regexFind": {
"input": "$name",
"regex": "(Company )|(Corporation )|(Corp )"
}
}
}
},
{
"$match": {
regexResObject: {
$ne: null
}
}
},
{
$addFields: {
newName: {
$replaceAll: {
input: "$name",
find: "regexResObject.match",
replacement: ""
}
}
}
},
{
"$project": {
regexResObject: 0
}
}
])

基于aaronlukacs的答案,但修复了不能在更新管道中使用match的事实:

db.customers.updateMany(
{  },
[
{
$addFields: {
regexResObject: {
$regexFindAll: {
input: '$name',
regex: '(Company )|(Corporation )|(Corp )'
}
}
}
},
{
$addFields: {
newName: {
$reduce: {
input: '$regexResObject',
initialValue: '$name',
in: {
$replaceAll: {
input: '$$value',
find: '$$this.match',
replacement: ''
}
}
}
}
}
},
{
$project: {
regexResObject: 0
}
}
]
)

注意,如果没有匹配,newName应该只是name。我还使用了regexFindAll,它将消除多个regex匹配实例…与此无关,但可能适用于其他情况。

最新更新