javascriptmongodbmongodb-queryclearml

Replacing IPs in MongoDB


I have a nested schema for mongoDB collection. It looks smth like this:

{
   "_id":"61d99bf5544f4822bd963bda0a9c213b",
   "execution": {
        "test_split":0,
        "artifacts":{
            "9ed39_output": {
                "uri": "http://100.com/somefile"
            },
            "8d777_output":{
                "uri": "http://100.com/anotherfile"
            }
        }
    }
}

Notice that artifacts keys are unique. I need to replace the ip stored in uri (in this dummy example "100") with some other ip (lets say "200"). I need to write some find and foreach. But I am really confused by variable keys under "artifacts". Any help is much appreciated. Thanks

Database is part of ClearML. There is an example how to change location for models: https://clear.ml/docs/latest/docs/faq/#relocate_models. But I couldnt succeed adapting that rather simple schema to this usecase.


Solution

  • Not fully clear how general you like to modify the document. In principle you can do it like this:

    db.collection.aggregate([
       { $set: { "execution.artifacts": { $objectToArray: "$execution.artifacts" } } },
       {
          $set: {
             "execution.artifacts": {
                $map: {
                   input: "$execution.artifacts",
                   in: {
                      k: "$$this.k",
                      v: {
                         uri: {
                            $replaceOne: {
                               input: "$$this.v.uri",
                               find: "100.",
                               replacement: "200."
                            }
                         }
                      }
                   }
                }
             }
          }
       },
       { $set: { "execution.artifacts": { $arrayToObject: "$execution.artifacts" } } },
    ])
    

    Mongo Playground

    Perhaps you need to do some enhancements in the $replaceOne part. Maybe you need regular expressions or you can $split the string, replace one element and join the array again with $reduce.