Chinese_hacker_lm
Chinese_hacker_lm

Reputation: 83

Add field and replace its characters with spaces mongodb aggregate

I'm trying to search for a record using the record's name .

So what i did :

let query={}
query.name = req.query.name;

      {
        $match: {
          ...query,
        },
      },

it is working fine.

What I'm looking for is to strip some white spaces and letters from the field name and replaces it with some letters, after that search with the new string on name

just like using the regular javascript to replace something based on a regex like :

let string = 'nice'

string.replace(new RegExp("([\u0622-\u0623-\u0625])"), "oof")

is this possible to do?

Upvotes: 1

Views: 173

Answers (1)

NeNaD
NeNaD

Reputation: 20304

You can do it with $replaceAll operator:

db.collection.aggregate([
  {
    "$match": {
      "name": "Naruto Uzumaki"
    }
  },
  {
    "$set": {
      "name": {
        "$replaceAll": {
          "input": "$name",
          "find": "Naruto",
          "replacement": "Boruto"
        }
      }
    }
  }
])

Working example

Upvotes: 1

Related Questions