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'}
]}
Bosworth99
  • 4,206
  • 5
  • 37
  • 52
  • 1
    It is not possible right now. You can read workaround here: [How to Update Multiple Array Elements in mongodb](http://stackoverflow.com/questions/4669178/how-to-update-multiple-array-elements-in-mongodb) . There is an open Issue in MongoDB for that feature: https://jira.mongodb.org/browse/SERVER-1243 – Bonanza Mar 23 '16 at 20:31

1 Answers1

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'},
        ]
    }
})
BanksySan
  • 27,362
  • 33
  • 117
  • 216
  • This is exactly what a statement I gave in answer to [How to Update Multiple Array Elements in mongodb](http://stackoverflow.com/a/33193231/5031275) 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. – Blakes Seven Mar 23 '16 at 21:58