Home > Back-end >  replace Regex with $replaceAll mongodb
replace Regex with $replaceAll mongodb

Time:06-21

I'm trying to replace all the unnecessary text in the field

For example I have this:

_id:12345678901,
name:"Company Z"

_id:12345678902,
name: "Corp Y"

_id:12345678902,
name: "Corporation X"

And I want to remove Corp, Corporation and Company in the field name, and make a new field for it, but I can't do it with regex

Target:

_id:12345678901,
name: "Company Z",
newName: "Z"

_id:12345678902,
name: "Corp Y",
newName: "Y"

_id:12345678902,
name: "Corporation X",
newName: "X"

Currently I have this:


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

But it doesn't seems to work.

BTW im using mongod 4.4.14

CodePudding user response:

The problem is that $regexFind doesn't return a string, but an object doc First you have to do $regexFind, and after use the returned objects match field to to the $replaceAll. Here is an example aggregation pipeline which transforms your objects to the desired ones:

  {
    $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
    }
  }
])
  • Related