By default, mongodb update command will update only one document.
db.collection.update({document to be found},{changes to be done})
To update multiple document, you should include multi keyword.
db.collection.update({document to be found},{changes to be done},{multi:true})
Assuming your document structure as below:
{
"_id": 5,
"body": "Correct horse battery staple",
"comments": [{"user_id": "123"},{"user_id": "456"},{"user_id": "123"}]
}
{
"_id": 6,
"body": "Correct horse battery staple",
"comments": [{"user_id': "23"},{"user_id": "123"},{"user_id": "13"}]
}
In this case, i may need to update multiple elements inside an array as well as multiple documents. There is no default mongodb query to do it.
Instead i will loop through documents and do it as follows.
// loop until all documents has been updated
while(db.post.find({'comments.user_id':'123'}).count()!=0)
{
db.post.update(
{ 'comments.user_id':'123' },
{ $set:{'comments.$.user_id':'abc'} },
{ multi:true }
)
}
After the 1st loop run, post collection will look like:
{
"_id": 5,
"body": "Correct horse battery staple",
"comments": [{"user_id": "abc"},{"user_id": "456"},{"user_id": "123"}]
}
{
"_id": 6,
"body": "Correct horse battery staple",
"comments": [{"user_id": "23"},{"user_id": "abc"},{"user_id": "13"}]
}
After the 2nd loop run, post collection will look like:
{
"_id": 5,
"body": "Correct horse battery staple",
"comments": [{"user_id": "abc"},{"user_id": "456"},{"user_id": "abc"}]
}
{
"_id": 6,
"body": "Correct horse battery staple",
"comments": [{"user_id": "23"},{"user_id": "abc"},{"user_id": "13"}]
}
In the third loop run, the loop gets terminated.