1

A question if I want to update all documents embedded in a document, how could I do? because when you run the following command

.update({'sites':{$elemMatch:{'status':true}}},{$set:{'sites.$.status': false}},{multi:true})

only the first found embedded document is updated

documents example:

{
  '_id': 1, 
  sites: [

    {'status':true,'url':'http://google.com'},
    {'status':true,'url':'https://university.mongodb.com'},
    {'status':true,'url':'https://docs.mongodb.org'}
]}
1

1 Answer 1

1

This isn't possible, the closes you can get is to update the entire element. e.g.:

db.test.update({
    _id: 1
},
{
    $set: {
        sites: [
            {'status':true,'url':'http://1.example.com'},
            {'status':true,'url':'http://2.example.com'},
            {'status':true,'url':'http://3.example.com'},
        ]
    }
})
Sign up to request clarification or add additional context in comments.

1 Comment

This is exactly what a statement I gave in answer to How to Update Multiple Array Elements in mongodb warns people not to do: 'Do not "one shot" update the array'. Whilst that practice may be acceptable in a data transformation with no update traffic, it is not safe to presume that the array members you "thought" were the only ones present at the time of issuing the update are "still" the only array members, or indeed in the same order ( should order be important, and also covered with another point ). You should read this yourself.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.