0

I have a collection with the following structure:

{
  arrangements: [
    { displayName: "MRT.8" },
    { displayName: "MRT.10" },
    { displayName: "MRT.12" },
    (...)
  ]
}

I want the substring MRT to be replaced with MOBILE, so the result will be as follows:

{
  arrangements: [
    { displayName: "MOBILE.8" },
    { displayName: "MOBILE.10" },
    { displayName: "MOBILE.12" },
    (...)
  ]
}

Following the solution for a similar problem on SO I did the following:

db.collection('releaseDocument').updateMany({"arrangements.displayName": {$regex: /MRT\..*/}}, [
      {
        $set: {
          'arrangements.displayName': {
            $concat: [
              "MOBILE.",
              {$arrayElemAt: [{$split: ["$displayName", "MRT."]}, 0]}
            ]
          }
        }
      }
    ])

But that doesn't work because $ refers to the current document, not the nested array element. How can I achieve what I described above?

1 Answer 1

1

Seems you are working with Update with Aggregation Pipeline, you need $map operator.

For $arrayElementAt part, I think you need 1 as an index to take the second element.

Assume that the filter returns documents to be updated:

db.collection.update({
  "arrangements.displayName": {
    $regex: /MRT\..*/
  }
},
[
  {
    $set: {
      "arrangements": {
        $map: {
          input: "$arrangements",
          in: {
            $mergeObjects: [
              "$$this",
              {
                displayName: {
                  $concat: [
                    "MOBILE.",
                    {
                      $arrayElemAt: [
                        {
                          $split: [
                            "$$this.displayName",
                            "MRT."
                          ]
                        },
                        1
                      ]
                    }
                  ]
                }
              }
            ]
          }
        }
      }
    }
  }
])

Sample Mongo Playground

Sign up to request clarification or add additional context in comments.

1 Comment

just what I needed. I didn't know the $$this operator only works when using $map. And you were right about using 1 as the index, too

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.