0

I've got the following document named "clients" which includes id, name and list of projects (array of objects):

{
    "_id": {
        "$oid": "572225d997bb651819f379f7"
    },
    "name": "ppg",
    "projects": [
        {
            "name": "aaa",
            "job_description": "",
            "projectID": 20
        },
        {
            "name": "bbbb",
            "job_description": "",
            "projectID": 21
        }
    ]
}

I would like to update "job_description" of project with given "projectID" like this:

module.exports.saveJobDesc = function(client, idOfProject, textProvided) {
    db.clients.update({ name: client}, 
    { $set: {'projects.0.job_description': textProvided }});
};

But instead of hardcoded index "0" of array I want to find specific project using "projectID". Is there a way to achieve this without changing the structure of collection and/or document?

1
  • What about using findOne to get the client object first and then iterating his projects manually? Commented Apr 28, 2016 at 20:50

2 Answers 2

1

If you want to update the "job_description" where name="ppg" and project_id=20 then you can use below mongo query:-

db.clients.update({ "name":"ppg","projects.projectID":20 },{$set: {"projects.$.job_description": "abcd"}})

Please let me know if any thing else is required

Sign up to request clarification or add additional context in comments.

Comments

0

You cannot update multiple array elements in single update operation, instead you can update one by one which takes time depends upon number of elements in array and number of such documents in collection. see New operator to update all matching items in an array

   db.test2.find().forEach( function(doc) {
    var projects = doc.projects;
    for(var i=0;i<projects.length;i++){
        var project = projects[i];
        if(project.projectID == 20){
            var field = "projects."+i+".job_description";
            var query = {};
            query[field] = "textasdsd";
            db.test2.update({ _id: doc._id},{ $set:query});
        }
}
})

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.