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.
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}})
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With