How to update a field in a nested JSON document in Mongo?
{
_id : '123'
friends: [
{name: 'allen', emails: [
{
video: {
name:'abc',
subType:'video',
status:'active'
}
},
{
video: {
name:'abc',
subType:'video',
status:'active'
}
}
]}
]
}
I have tried the following query but I am not able to update the document.
db.users.update ({_id: '123'}, {$set: {"friends.0.emails.0.video.status" : 'Inactive'} })
Best Answer
As per MongoDB documentaion here The update method can modify specific fields of an existing document or documents or replace an existing document entirely, depending on the update parameter.
By default, the update() method updates a single document. Set the Multi Parameter to update all documents that match the query criteria.
The
update()
method has the following form:Changed in version 3.6.
For example to update the JSON documents through update command in mongo shell, which you have been mention.
Here I have created the test database & also users collection based on your mention documents.
Now I want to see the inserted documents in users collections in mongo shell through the command such as
As you want to update the status : Inactive , which comes under the metadata of video. The update statement command will be as follows
Again I will check through the find method , it has been modified or not.