MongoDB : how to set a new field equal to the value of another field, for every document in a collection [duplicate]

本小妞迷上赌 提交于 2019-12-18 17:36:29

问题


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.


回答1:


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}})
});


来源:https://stackoverflow.com/questions/39036206/mongodb-how-to-set-a-new-field-equal-to-the-value-of-another-field-for-every

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!