MongoDB update multiple records of array [duplicate]

You cannot modify multiple array elements in a single update operation. Thus, you’ll have to repeat the update in order to migrate documents which need multiple array elements to be modified. You can do this by iterating through each document in the collection, repeatedly applying an update with $elemMatch until the document has all of its relevant comments replaced, e.g.:

db.collection.find().forEach( function(doc) {
  do {
    db.collection.update({_id: doc._id,
                          comments:{$elemMatch:{user:"test",
                                                avatar:{$ne:"new_avatar.jpg"}}}},
                         {$set:{"comments.$.avatar":"new_avatar.jpg"}});
  } while (db.getPrevError().n != 0);
})

Note that if efficiency of this operation is a requirement for your application, you should normalize your schema such that the location of the user’s avatar is stored in a single document, rather than in every comment.

Leave a Comment