MongoDB:如何为集合中的每个文档设置一个新字段,该字段等于另一个字段的值
问题描述:
我需要运行迁移脚本,以将值(每个文档中已有)插入到同一文档的数组中.必须对我的收藏中的每个文档执行此操作(无需选择查询)
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)
如何更改此设置:
{
"_id": ObjectID("5649a7f1184ebc59094bd8b3"),
"alternativeOrganizer": ObjectID("5649a7f1184ebc59094bd8b1"),
"myArray": []
}
对此:
{
"_id": ObjectID("5649a7f1184ebc59094bd8b3"),
"alternativeOrganizer": ObjectID("5649a7f1184ebc59094bd8b3"),
"myArray": [
ObjectID("5649a7f1184ebc59094bd8b3")
]
}
谢谢.
答
我将使用 forEach 和 $ addToSet ,以便脚本可以重新执行. /p>
I would use forEach and $addToSet, so that the script can be re-executable.
$ addToSet运算符将一个值添加到数组,除非该值是 已经存在,在这种情况下,$ addToSet对该数组不执行任何操作.
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}})
});