Search code examples
arraysmongodbmongodb-update

Update Array using $in and $addtoSet Mongodb


I am using $in and $addToSet to update an array in my collections. Say I have this kind of my documents.

{ 
    _id: objectId(1), //this is just an example id
    names: ['harry', 'hermione']
},
{
    _id: objectId(2),
    names: ['ron']
},
{
    _id: objectId(3),
    names: ['dumbledoor']
}

I want to update all of this documents so I have an array of ids

var arr_ids = [1, 2];

and use the array map like this.

var ids = arr_ids.map(function(id) { return mongoose.Types.ObjectId(id); });

To update all the documents in my collections.

db.update( { _id: { $in: ids } }, { $addToSet: { name : 'draco' } }, 
    function(err, results) {
      if(err) console.log(err);
      console.log(results);
    }
);

I use the $in and $addToSet and it works and updates the document but it only updates the last document.

{ 
    _id: objectId(1), //this is just an example id
    names: ['harry', 'hermione']
},
{
    _id: objectId(2),
    names: ['ron', 'draco'] // it only update this document.
},
{
    _id: objectId(3),
    names: ['dumbledoor']
}

I don't know why. I don't want to create a for loop just to update it individually, but it seems to me that's my last resort. Please help me out. Thanks!


Solution

  • Try it with multi: true like so

    db.update( /*query*/, { $addToSet: { names : 'draco' } }, {multi:  true} ...
    

    See multi-parameter and this example for the documentation for it