我有一个MongoDB集合,其中有许多这样的对象:

{
 "_id" : "1234", 
 "type" : "automatic", 
 "subtypes" : [
    {
     "_id" : "dfgd",
     "name" : "test subtype", 
     "subjetRequired" : true,
    },
    {
     "_id" : "dfgd",
     "name" : "test subtype2", 
     "subjetRequired" : false,
    }
  ],
 "anotherField" : "some value"
}

As you can see, one of the keys in the subtypes array is incorrectly spelled - "subjetRequired" instead of "subjectRequired".
I want to correct that key name. How can I do that.
I'll preface this by saying I've not worked with mongodb very much in the past.
After a lot of researching, the best I could come up with is the following (which doesn't work):

function remap(doc) {
     subtypes = doc.subtypes;
     var count = 0;
     subtypes.forEach(function(subtype){
         db.taskType.update({"_id": subtype._id}, {
             $set: {"subtypes.subjectRequired" : subtype.subjetRequired},
             $unset: {"subtypes.subjetRequired": 1}
         });
     }
     )
}

db.taskType.find({"subtypes.subjetRequired":{$ne:null}}).forEach(remap);

This doesn't work.
I know the loop is correct, as if I replace the other logic with print statements I can access and print the fields who's names I want to modify.
What am I doing wrong here?

推荐答案

你可以使用这个更新,避免使用任何代码,它也很稳定,所以你可以无所畏惧地多次执行它.

db.collection.updateMany({
  "subtypes.subjetRequired": {
    $exists: true
  }
},
[
  {
    $set: {
      subtypes: {
        $map: {
          input: "$subtypes",
          in: {
            $mergeObjects: [
              "$$this",
              {
                subjectRequired: "$$this.subjetRequired",
                
              }
            ]
          }
        }
      }
    }
  },
  {
    $unset: "subtypes.subjetRequired"
  }
])

Mongo Playground

Mongodb相关问答推荐

MongoDB$unionWith,如何 Select 特定文档

执行聚合以消除重复并获得唯一计数

将子元素的数组值提取到 mongodb 中的单个数组中?

MongoDB DB参考返回null值

如何在MongoDB中搜索有序子集的方法?

定期自动轮换 MongoDb 集合

MongoDB:通过嵌套数组中的最后一个元素值获取文档

有谁知道这个错误的修复方法(TypeError: Cannot assign to read only property ‘map’ of object '#')

为什么使用整数作为 pymongo 的键不起作用?

是否可以迭代 mongo 游标两次?

MongoDB 的 Java 语法

Stripe:必须提供来源或客户

如何使用 java 驱动程序更新 mongo db 中的文档字段?

是否有适用于 Linux 的 MongoDB GUI 桌面应用程序?

带有 jQ​​uery Ajax/JSON 前端的 MongoDB 或 CouchDB 中间件

Ruby 按键值分组哈希

用于嵌入式集合的 MongoDB 首选模式.文档与数组

为什么我新创建的 mongodb 本地数据库增长到 24GB?

如何在mongoDB中检索其值以特定字符结尾的文档

MongoDB Compass timeouts超时