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

526
Vistas
Update nested object in array MongoDB

I need to find and update documents with category that corresponding to the query. Array could contain mo than one corresponding id.

Query:

{
 "ids": ["61f1cda47018c60012b3dd01", "61f1cdb87018c60012b3dd07"],
 "userId": "61eab3e57018c60012b3db3f"
}

I got collection with documents like:

`{

   "_id":{"$oid":"61f1cdd07018c60012b3dd09"},
   "expenses":[
     {"category":"61eafc104b88e154caa58616","price":"1111.00"},                  
     {"category":"61f1cdb87018c60012b3dd07","price":"2222.00"}, 
     {"category":"61f1cda47018c60012b3dd01","price":"1241.00"}, 
     {"category":"61f1cdb87018c60012b3dd07","price":"111.00"}
   ],
   "userId":"61eab3e57018c60012b3db3f"
 }`

my method:

  async myMethod(ids: [string], userId: string) {
try {
  const { ok } = await this.ExpensesModel.updateMany(
    {"userId": userId, "expenses.category": { $in: ids }},
    {$set: {"expenses.$.category": "newCategoryID"}}
  );
  return ok
} ........

I path array of ids ["61f1cda47018c60012b3dd01","61f1cdb87018c60012b3dd07","61f1cdb87018c60012b3dd07"] and userId, this code update only 1 category by document.

So can i made it with mongo build in methods? or i need to find matching document and update it it by my self and after that update or insert;

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

0

Update with arrayFilters

db.collection.update({
  "expenses.category": {
    $in: [
      "61f1cda47018c60012b3dd01",
      "61f1cdb87018c60012b3dd07"
    ]
  }
},
{
  $set: {
    "expenses.$[elem].category": "61eab3e57018c60012b3db3f"
  }
},
{
  arrayFilters: [
    {
      "elem.category": {
        $in: [
          "61f1cda47018c60012b3dd01",
          "61f1cdb87018c60012b3dd07"
        ]
      }
    }
  ]
})

mongoplayground

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