Anuj Verma
Anuj Verma

Reputation: 23

How to update a field value in array in mongo database?

How can we update a value for 'Enabled' field in Configuration at index 1 in Configurations Array in mongo database ?

Below is my Json data.

{
    "Configurations" : [ 
                           {
                               "Configuration" : {
                                   "Host" : "",
                                   "Port" : "1521",
                                   "Enabled" : "true"                 
                               }
                            }, 
                            {
                               "Configuration" : {
                               "Host" : "",
                               "Port" : "",
                               "Enabled" : "true"
                               }                                  
                            }
                        ],
    "Description" : "Check Database Server"                   
}

Is there any way to update value for Enabled field in Configuration ?? How can we update a value for 'Enabled' field in Configuration at index 1 in Configurations Array in Mongodba ?

I want to update Enabled field value of 2nd configuration in Configurations Array.

Upvotes: 0

Views: 70

Answers (2)

Vishwas
Vishwas

Reputation: 7067

Try this:

db.collection.update({
"Configurations": {
    "$elemMatch": {
        "Configuration.Port": "1521"
    }
}
}, {
"$set": {
    "Configurations.$.Configuration.Enabled": "false"
}
})

Upvotes: 0

Sede
Sede

Reputation: 61293

What about something like this

db.collection.update({}, 
    { "$set": { "Configurations.1.Configuration.Enabled": false }}
)

Upvotes: 2

Related Questions