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

188
Vistas
Conditional array update MongoDB

I have a collection like this one:

{
"citizen":[
  {
    "country":"ITA",
    "language":"Italian"
  },
  {
    "country":"UK",
    "language":"English"
  },
  {
    "country":"CANADA",
    "language":"French"
  }]
}

I'm trying to update the collection but with a certain condition. I need to update remove an element of the array citizen if the value in the field country is longer than 3 characters.

I got that to remove an element i have to use $pull, to check the size of a string I have to use $strLenCP and $gt is greater than, but I'm struggling to put them together.

The result of the update should be:

{
"citizen":[
  {
    "country":"ITA",
    "language":"Italian"
  },
  {
    "country":"UK",
    "language":"English"
  }]
}

Any suggestions?

EDIT: with the collection, as it is, the command:

db.getCollection('COLLECTION').update(  { }, {  $pull:  {"citizen": {"country": /^[\s\S]{4,}$/}}}, { multi: true })

works perfectly. I tried it on another collection as this one:

{
"cittadino":{
  "citizen":[
    {
      "country":"ITA",
      "language":"Italian"
    },
    {
      "country":"UK",
      "language":"English"
    },
    {
      "country":"CANADA",
      "language":"French"
    }]
  }
}

and it doesn't update anymore. What should i do?

over 4 years ago · Santiago Trujillo
1 Respuestas
Responde la pregunta

0

You're on the right path:

db.getCollection('COLLECTION').update(  { }, {  $pull:  {"citizen": {"country": /^[\s\S]{4,}$/}}}, { multi: true })

$pull operator takes a value or a condition. You need to use this to filter the array based on the "country" property

EDIT:

Use the dot-notation to access the nested document

db.getCollection('COLLECTION').update(  { }, {  $pull:  {"cittadino.citizen": {"country": /^[\s\S]{4,}$/}}}, { multi: true })
over 4 years ago · Santiago Trujillo 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