Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

126
Views
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 answers
Answer question

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 Report

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 Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!