Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

how can I modify a field name / key in a nested array of objects in mongodb?

I have a mongodb collection with a number of objects like this:

{
 "_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?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

You can use this update and avoid using any code, it’s also stable so you can execute it multiple times with no fear.

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

Mongo Playground

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading