dominik791
dominik791

Reputation: 752

Update object with given ID embed in array without restructuring Mongo database

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?

Upvotes: 0

Views: 71

Answers (2)

Ankit Aneja
Ankit Aneja

Reputation: 110

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

Upvotes: 1

achuth
achuth

Reputation: 1212

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});
        }
}
})

Upvotes: 0

Related Questions