how to update fields of a nested object in mongodb?

Salam (means Hello) :)

I'm using node-mongodb-native driver and I need to update specific fields of objects stored in an array. this is a sample document in my mongodb collection:

{
    "fields" : [ 
        {
            "en" : "birthDate",
            "status" : "enable",
            "index" : 10
        },{
            "en" : "email",
            "status" : "enable",
            "index" : 4
        },{
            "en" : "inviterCode",
            "status" : "enable",
            "index" : 2
        }
    ]
}

and this is my new data:

var newData = [ 
    {
        "en" : "birthDate",
        "status" : "disable",
    },{
        "en" : "email",
        "status" : "disable",
    }
];

as you can see, if en field matches, status field should be updated. I know that following query works for a single update, but how can I achieve multiple updates with a single query?

collection.update(
    {'fields.en': 'birthDate'}, 
    {$set:{'fields.$.status': 'disable'}}, 
    {w:1, multi: true}, 
    function(error, count){

    }
);

Leave a Reply

Your email address will not be published. Required fields are marked *