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

377
Visualizações
MongoDB: updating 2 arrays in the same document

User:

{
_id: "userID",
array_1:[],
array_2:[]
}

I need to do two updates to this document:

  1. array_1 contains objects with unique id property. I need to find one where id=targetID and replace it with the newObject, like this:
User.updateOne(
    {
      _id: userID, 
      "array_1.id": targetID
    }, 
     {
       "$set":{"array_1.$":newObject}
     }
  )
  1. array_2 contains objects, where multiple objects can have same id values. I need to update 2 properties of all objects in the array_2 where id=targetID, like this:
User.updateOne(
  { 
    _id: userID, 
    "array_2.id": targetID
  },
  { 
    "$set": { 
              "array_2.$[elem].property_1": new_property_1, 
              "array_2.$[elem].property_2": new_property_2 
            } 
  },
  { 
    "arrayFilters": [{ "elem.id": targetID }], 
    "multi": true 
  }
  )

These two work fine if I run it separately, but how do I combine both in one function?

over 4 years ago · Santiago Trujillo
1 Respostas
Responde à pergunta

0

You can combine it using arrayFilters, same as you did nin second query,

  • create a filters property arr1 and use it to update object,
await User.updateOne(
  { _id: userID },
  {
    $set: {
      "array_1.$[arr1]": newObject,
      "array_2.$[elem].property_1": new_property_1,
      "array_2.$[elem].property_2": new_property_2
    }
  },
  {
    arrayFilters: [
      { "elem.id": targetID },
      { "arr1._id": targetID }
    ]
  }
)
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