Home > OS >  How do I update a specific property of a nested array element in MongoDB
How do I update a specific property of a nested array element in MongoDB

Time:05-04

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 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?

CodePudding user response:

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

  • Related