How to replace dynamic keys in mongodb?

Viewed 61
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.

1 Answers

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

EDIT: If you consider each dictionary here can have several keys and you want all keys to be generic (as they should), you can use $map as each key can contain array of items:

db.collection.aggregate([
  {$project: {GENUS_DATA: {$objectToArray: "$GENUS_DATA"}}},
  {
    $project: {
      GENUS_DATA: {
        $map: {
          input: "$GENUS_DATA",
          as: "item",
          in: {"File-Name": "$$item.k", met: {$objectToArray: "$$item.v"}}
        }
      }
    }
  },
  {
    $project: {
      GENUS_DATA: {
        $map: {
          input: "$GENUS_DATA",
          as: "file",
          in: {"File-Name": "$$file.File-Name",
            met: {
              $map: {
                input: "$$file.met",
                as: "met",
                in: {"METNO": "$$met.k", data: "$$met.v"}
              }
            }
          }
        }
      }
    }
  }
])

See how it works on the playground example - generic multi keys

Related