0

I went through this link: How to rename a document field in a MongoDB?, but its not working fine for me. I've Mongo Document like below. I am using 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",
            ....
            ....
        }, 
        ...
        ....
        .....
    ],
    ...
    ...
    ...
}

I executed the below query:

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

Error: cannot use the part (department of department.deptName) to traverse the element

Sarfraaz
  • 1,273
  • 4
  • 15
PAA
  • 1
  • 46
  • 174
  • 282
  • For fields in embedded documents, the $rename operator can rename these fields as well as move the fields in and out of embedded documents. $rename does not work if these fields are in array elements. please show this link https://docs.mongodb.com/manual/reference/operator/update/rename/ – Mayur Vaghasiya Feb 10 '20 at 12:13
  • also visite this link. https://stackoverflow.com/questions/9122966/mongodb-rename-database-field-within-array – Mayur Vaghasiya Feb 10 '20 at 12:18

1 Answers1

1

In Mongo 4.2 you could run this one:

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

I assume in 4.0.3. you have to modify the field name one-by-one with a loop in JavaScript

Wernfried Domscheit
  • 54,457
  • 9
  • 76
  • 110