Home > Enterprise >  How to update array of object property's value to new value mongodb?
How to update array of object property's value to new value mongodb?

Time:10-20

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?

CodePudding user response:

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

CodePudding user response:

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.

  • Related