首页 > 解决方案 > 更新嵌入式文档 Mongo 字段名称

问题描述

我浏览了这个链接:如何在 MongoDB 中重命名文档字段?,但它不适合我。我有如下的 Mongo 文档。我正在使用MongoDB server version: 4.0.3.

{
    "_id" : ObjectId("5cb825e566135255e0bf38a4"),
    "firstName" : "John",
    "lastName" : "svc_user",
    .....
    .....
    "status" : "A",
    "effDate" : ISODate("2012-08-24T01:46:33.000Z"),
    "department" : [ 
        {
            "deptName" : "KG",
            ....
            ....
        }, 
        ...
        ....
        .....
    ],
    ...
    ...
    ...
}

我执行了以下查询:

db.employee.update({}, {$rename:{"department.deptName":"department.departmentName"}}, false, true);

错误:无法使用部分(department.deptName的部门)遍历元素

标签: mongodb

解决方案


在 Mongo 4.2 你可以运行这个:

db.collection.updateMany(
   {
      department: { $exists: true },
      "department.deptName": { $exists: true }
   },
   [{
      $set: {
         department: {
            $map: {
               input: "$department",
               in: { departmentName: "$$this.deptName" }
            }
         }
      }
   }]
)

我假设在 4.0.3 中。您必须使用 JavaScript 中的循环一一修改字段名称


推荐阅读