Home > Back-end >  How to replace dynamic keys in mongodb?
How to replace dynamic keys in mongodb?

Time:06-21

I have multiple documents of below structure.

"GENUS_DATA": {
        "File_6489248.ZLM": {
            "MeterID_6489248": {}
                            }
              }

"GENUS_DATA": {
        "File_12345.ZLM": {
            "MeterID_12345": {}
                          }
              }

I want to replace File_6489248.ZLM and File_12345.ZLM with name "File-Name" AS KEY dynamically in mongo-Db remember there will be n number of records so defining only the above 2 values will not work.

CodePudding user response:

One option is to use $objectToArray with update pipeline:

db.collection.update({},
[
  {$set: {GENUS_DATA: {$objectToArray: "$GENUS_DATA"}}},
  {$project: {GENUS_DATA: {"File-Name": {$first: "$GENUS_DATA.k"},
        "data": {$first: "$GENUS_DATA.v"}}}
  }
],
{multi: true})

See how it works on the playground example

  • Related