4

I need to run a migration script to insert a value (already available in each document) into an array of this same document. This has to be done for each documents of my collection (no selection query required)

How to change this:

{
    "_id": ObjectID("5649a7f1184ebc59094bd8b3"),
    "alternativeOrganizer": ObjectID("5649a7f1184ebc59094bd8b1"),
    "myArray": []
}

Into this:

{
    "_id": ObjectID("5649a7f1184ebc59094bd8b3"),
    "alternativeOrganizer": ObjectID("5649a7f1184ebc59094bd8b3"),
    "myArray": [
         ObjectID("5649a7f1184ebc59094bd8b3")
    ]
}

Thanks in advance.

Vince Bowdren
  • 8,326
  • 3
  • 31
  • 56
franchez
  • 567
  • 1
  • 7
  • 20
  • 2
    May I know what is the problem in the below solution? Did I understood it wrongly? My understanding is that you wanted to update the existing records into the sample as mentioned? – notionquest Aug 19 '16 at 11:38
  • Who ever is down voting, can you please explain as well? What is wrong in the answer? Only down vote won't help us. – Shrabanee Aug 19 '16 at 11:45
  • 1
    db.s.find().forEach(function(obj){var id = obj._id;db.s.update({_id:id},{"$push":{"myArray":id}})}) – Ishan Soni Aug 19 '16 at 12:28

1 Answers1

13

I would use forEach and $addToSet, so that the script can be re-executable.

The $addToSet operator adds a value to an array unless the value is already present, in which case $addToSet does nothing to that array.

db.collectionname.find().forEach(function(results)
{    
    print( "Id: " + results._id );
    db.collectionname.update( {_id : results._id},
                       {$addToSet : {myArray : results._id}})
});
notionquest
  • 37,595
  • 6
  • 111
  • 105