Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

303
Vistas
Mongodb - update replacing a pattern of an array element

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

about 4 years ago · Juan Pablo Isaza
1 Respuestas
Responde la pregunta

0

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"
              }
          }
      }
  }
])
about 4 years ago · Juan Pablo Isaza Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda