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

128
Vistas
How to update array of object property's value to new value mongodb?

I have such a collection:

{
 "name": "Citroen",
 "additionals": [ "tires", "windows", "seats", "belts" ],
 "price": [ { "poor": 15.00 }, { "mid": 21.00 }, { "exl": 30.00 } ]
}

and I would like to make a modification of the price of verison for example mid from 21 to 23, I tried this:

function mod(name, version, newprice){  
    
    results = db.Cars.update({"name":name}, {$set: {"price.[0].$":newprice}});
    return results;
    }


mod("Citroen", "mid", 23)

can you tell me what am I doing wrong?

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

0

You can try positional update using $, $exists to check property exists in an array of object, put async/await for update query,

async function mod(name, version, newprice){  
  return await db.Cars.update(
    { 
      "name": name,
      ["price."+version]: { $exists: true }
    }, 
    { $set: { ["price.$."+version]: newprice } }
  );
}
mod("Citroen", "mid", 23);

Playground

about 4 years ago · Juan Pablo Isaza Denunciar

0

Since you are using JS you can create the key object so you can use something like this:

async function mod(name, version, newprice){ 
    var setObj = {}
    var setQuery = "price.$."+version
    setObj[setQuery] = newprice
    var findQuery = "price."+version
    var findObj = {name:name}
    findObj[findQuery]={$exists:true}
    

    results = await db.Cars.update(findObj, {$set:setObj});
    return results;
    }

mod("Citroen", "mid", 23)

Example how query works here

also don't forget async/await.

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