MongoDB:如何为集合中的每个文档设置一个新字段等于另一个字段的值 [英] MongoDB : how to set a new field equal to the value of another field, for every document in a collection

查看:28
本文介绍了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,以便脚本可以重新执行.

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屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆