集合中每个文档的 MongoDB : how to set a new field equal to the value of another field,

标签 mongodb mongodb-query

<分区>

我需要运行一个迁移脚本来将一个值(已经在每个文档中可用)插入到同一文档的数组中。必须对我收藏的每个文档执行此操作(无需选择查询)

如何改变这个:

{
    "_id": ObjectID("5649a7f1184ebc59094bd8b3"),
    "alternativeOrganizer": ObjectID("5649a7f1184ebc59094bd8b1"),
    "myArray": []
}

进入这个:

{
    "_id": ObjectID("5649a7f1184ebc59094bd8b3"),
    "alternativeOrganizer": ObjectID("5649a7f1184ebc59094bd8b3"),
    "myArray": [
         ObjectID("5649a7f1184ebc59094bd8b3")
    ]
}

提前致谢。

最佳答案

我会使用 forEach$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 : how to set a new field equal to the value of another field,,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39036206/

相关文章:

javascript - 循环数组并检查循环中的 MongoDB 集合(异步)

MongoDB geoNear 命令结果距离(以千米为单位)

javascript - 如何在mongodb中获取更新查询WriteResult

mongodb - 在 mongodb 中聚合每小时、每周、每月、每年的数据

javascript - Mongodb 聚合嵌套组与最近更新的文档

node.js - 关于使用 Node 和 mongo 迁移到 TDD

javascript - 如何从 Mongoose 的集合中排除一个特定字段?

MongoDB : Is there a way to detect a value trend using aggregation?

mongodb - 如何获取mongodb聚合中两个日期之间的工作日数

c++ - MongoDB C++ 更新数组并添加元素