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.

3
  • 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? Commented Aug 19, 2016 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. Commented Aug 19, 2016 at 11:45
  • 1
    db.s.find().forEach(function(obj){var id = obj._id;db.s.update({_id:id},{"$push":{"myArray":id}})}) Commented Aug 19, 2016 at 12:28

1 Answer 1

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}})
});
Sign up to request clarification or add additional context in comments.

1 Comment

Exactly what I need. Thanks.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.