Home > Blockchain >  Mongodb - update replacing a pattern of an array element
Mongodb - update replacing a pattern of an array element

Time:09-23

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 :)

CodePudding user response:

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