MongoDB:如何为集合中的每个文档设置一个新字段,该字段等于另一个字段的值 [英] MongoDB : how to set a new field equal to the value of another field, for every document in a collection
本文介绍了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}})
});
这篇关于MongoDB:如何为集合中的每个文档设置一个新字段,该字段等于另一个字段的值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文