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

174
Visualizações
Mongoose not updating multiple matches
[
  {
    "id": 1,
    "items": [
      {
        id: 15,
        score: 10
      },
      {
        id: 14,
        score: 100
      },
      {
        id: 12,
        score: 1
      }
    ]
  },
  {
    "id": 2,
    "items": []
  }
]

Now, I try to update items whose id is 14,15 & used the following query.

db.collection.update({
  "items.id": {
    $in: [
      14,
      15
    ]
  }
},
{
  $set: {
    "items.$.score": 444
  }
},
{
  multi: true
}
)

but it updated only the first match in items that is that is id with 15, what can be wrong?

[
  {
    "_id": ObjectId("5a934e000102030405000000"),
    "id": 1,
    "items": [
      {
        "id": 15,
        "score": 444
      },
      {
        "id": 14,
        "score": 100
      },
      {
        "id": 12,
        "score": 1
      }
    ]
  },
  {
    "_id": ObjectId("5a934e000102030405000001"),
    "id": 2,
    "items": []
  }
]
over 4 years ago · Santiago Trujillo
2 Respostas
Responde à pergunta

0

You can do it with Positional identifiers $[]

db.collection.update({
  "items.id": {
    $in: [
      14,
      15
    ]
  }
},
{
  $set: {
    "items.$[element].score": 444
  }
},
{
  arrayFilters: [
    {
      "element.id": {
        $in: [
          14,
          15
        ]
      }
    }
  ],
  multi: true
})

try it here

over 4 years ago · Santiago Trujillo Relatório

0

Use arrayFilters with targeted array elements: here is the doc

db.collection.update({
  "id": 1
},
{
  "$set": {
    "items.$[ele].score": 20
  }
},
{
  arrayFilters: [
    {
      "ele.id": {
        "$in": [
          15,
          14
        ]
      }
    }
  ]
})

see play ground code https://mongoplayground.net/p/cdgu1aqLwsI

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