Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

187
Visualizações
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 Respostas
Responde à pergunta

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda