Update many with a dynamic key

Hi
I would like to update all documents which match a specific string which is under a dynamic path: analysis.1234.labelings.dblabel. The 1234 is unfortunately not fixed. I want to update the string “dblabel old” to a “new string”.

I have a document structure like this:

{
  "studyID": "ABC",
  "Condition": "Healthy",
  "analysis": {
    "1234": { // dynamic key 
      "labelings": {
        "leiden": "0",
        "dblabel": "dblabel old"
      }
    }
  }
}

I thought I already found a solution using aggregations:

[
  {
    $set: {
      analysis: {
        $objectToArray: "$analysis",
      },
    },
  },
  {
    $match: {
      "analysis.v.labelings.dblabel":
        "dblabel old",
    },
  },
  {
    $set: {
      "analysis.v.labelings.dblabel": "new string",
    },
  },
  {
    $set: {
      analysis: {
        $arrayToObject: "$analysis",
      },
    },
  },
]

But unfortunately, aggregations do not change the DB. Then I need to use updateMany() apparently? But when I put my aggregations into a an updateMany() command I get this error:
MongoServerError: $match is not allowed to be used within an update

Now I am stuck and unsure how to proceed? Although I almost got what I wanted, I can not use it with a update command. Could you point me in the right direction on how to achieve my goal?
Thanks
Manuel


MongoDB Version 4.4.2

Hello, @Manuel_Kohler ! Welcome to the MongoDB community! :wave:

To persist updated document, you can just add $merge stage at the end of your pipeline:

{
  $merge: {
    into: 'yourCollectionName',
    on: '_id',
    whenMatched: 'merge',
    whenNotMatched: 'discard'
  }
}

This topic was automatically closed 5 days after the last reply. New replies are no longer allowed.