0

Given: a document as below

{
    _id: ObjectId("5eb...."),
    jobId: '40297467',
    aliases: [aX1, bX2_0, cX1X9_0]
}

When: combinations X1...X9 are not welcome in any of aliases

Then: I want to have a mongo native elegant way to replace an appropriate regex pattern with an empty string, so, as a result, I have the document as below:

{
    _id: ObjectId("5eb...."),
    jobId: '40297467',
    aliases: [a, b_0, c_0]
}

Homework done:

Here MONGO mongodb script to replace a substring from a array element there is a solution for cases where you do not need pattern and have a simple string to replace, however, it is of not much use - since aggregation replaceAll find argument "any valid expression that resolves to a string or a null" (https://docs.mongodb.com/manual/reference/operator/aggregation/replaceAll/) So, if I use pattern it just does not work.

mongo forEach loop does the job but it looks a bit ugly for me... Besides, I'm not sure what will be the price of such looping.

db.col.find({ jobId: "40297467" }).forEach(function (x) {
  const regex = /*pattern*/gi;
  array = []
  for (let alias of x.aliases) {
    array.push(alias.replace(regex, ""));
  }
  db.col.update({ _id: x._id }, { $set: { aliases: array} });
});

Any help would be much appreciated :)

1 Answer 1

1

This update with aggregation pipeline works with MongoDB v4.4 (uses the $function aggregate operator):

db.collection.updateMany(
{ },
[
  { 
      $set: { 
          aliases: {
              $function: {
                  body: function(arr) {
                               arr = arr.map(e => e.replace(/x\d/gi, ""));
                               return arr;
                  },
                  args: [ "$aliases" ],
                  lang: "js"
              }
          }
      }
  }
])
Sign up to request clarification or add additional context in comments.

3 Comments

just to clarify - does this solution of yours have any performance benefits in comparison with find().forEach() in the question? Besides refactor of course since I suppose line arr = arr.map(e => e.replace(/x\d/gi, "")); can be used in my solution too.
The statement arr = arr.map(e => e.replace(/x\d/gi, "")); is pure JavaScript; so you can use it in your code too. The benefit of using the update with aggregation pipeline (the solution) would be that the entire code (including the JS function) runs on the MongoDB database server. You submit the update, the update happens on the server and you get the the update confirmation. Your code deals with a read (find makes a call to the database), process on the client program and then an update on the server.
ok, cool, thx for the explanation and your time

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.