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

122
Vistas
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?

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

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 }
    ]
  }
)
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