MongoDB: Rename field in array with nested document

I struggle to rename a fieldname within a nested document in an array in MongoDB:

[
  {
    "parserErgebnis": [
      {
        "values": {
          "NUTZERKENNUNGAUFTRAGGEBER": {
            "status": "OK",
            "wert": "1000/13138/1082"
          },
          "ANYTHING": "bla",
          "BLUBB": "bla"
        }
      }
    ]
  },
  {
    "parserErgebnis": [
      {
        "values": {
          "NUTZERKENNUNGAUFTRAGGEBER": {
            "status": "OK",
            "wert": "1000/13138/1083"
          }
        }
      }
    ]
  },
  {
    "parserErgebnis": [
      {
        "values": {
          "ORDNUNGSBEGRIFFAUFTRAGGEBER": {
            "status": "OK",
            "wert": "1000/13138/1084"
          }
        }
      }
    ]
  }
]

NUTZERKENNUNGAUFTRAGGEBER must be renamed to ORDNUNGSBEGRIFFAUFTRAGGEBER.

So, the result should look like that:

[
  {
    "parserErgebnis": [
      {
        "values": {
          "ORDNUNGSBEGRIFFAUFTRAGGEBER": {
            "status": "OK",
            "wert": "1000/13138/1082"
          },
          "ANYTHING": "bla",
          "BLUBB": "bla"
        }
      }
    ]
  },
  {
    "parserErgebnis": [
      {
        "values": {
          "ORDNUNGSBEGRIFFAUFTRAGGEBER": {
            "status": "OK",
            "wert": "1000/13138/1083"
          }
        }
      }
    ]
  },
  {
    "parserErgebnis": [
      {
        "values": {
          "ORDNUNGSBEGRIFFAUFTRAGGEBER": {
            "status": "OK",
            "wert": "1000/13138/1084"
          }
        }
      }
    ]
  }
]

I tried this which doesn’t work. The problem is that parserErgebnis.values.ORDNUNGSBEGRIFFAUFTRAGGEBER is throwing an error. What works is just ORDNUNGSBEGRIFFAUFTRAGGEBER, but with that values sub-document is gone.

db.collection.update({
  "parserErgebnis.values.NUTZERKENNUNGAUFTRAGGEBER": {
    $exists: true
  }
},
[
  {
    $addFields: {
      parserErgebnis: {
        $map: {
          input: "$parserErgebnis",
          as: "parserErgebnis",
          in: {
            "parserErgebnis.values.ORDNUNGSBEGRIFFAUFTRAGGEBER": "$$parserErgebnis.values.NUTZERKENNUNGAUFTRAGGEBER"
          }
        }
      }
    }
  }
],
{
  multi: true
})

Any ideas? I appreciate your help.
https://mongoplayground.net/p/N6pjj8J_Vme

>Solution :

Try this:

db.collection.update({
  "parserErgebnis.values.NUTZERKENNUNGAUFTRAGGEBER": {
    $exists: true
  }
},
[
  {
    $addFields: {
      parserErgebnis: {
        $map: {
          input: "$parserErgebnis",
          as: "parserErgebnis",
          in: {
            "values": {
              ORDNUNGSBEGRIFFAUFTRAGGEBER: "$$parserErgebnis.values.NUTZERKENNUNGAUFTRAGGEBER"
            }
          }
        }
      }
    }
  }
],
{
  multi: true
})

Mongo Playground

Leave a Reply