3

I'm using MongoDB v4.4. My document structure looks like this:

{
  _id: ObjectId("..."),
  photos: ["image1.png", "image2.png"]
},
{
  _id: ObjectId("..."),
  photos: ["image3.png", "another_image.png, image5.jpg"]
},
{
  _id: ObjectId("..."),
  photos: ["image_name.jpg", "image2.jpg"]
},

I am trying to change all the strings that contain ".png" to ".jpg".

I have tried the following:

db.users.updateMany({
  photos: { $regex: /.png/ }
}, [{
  $set: {
    "photos.$[]": { 
      $replaceOne: { 
        input: "photos.$[]", find: ".png", replacement: ".jpg" 
      } 
    }
  }
}])

This returns the error:

MongoServerError: Invalid $set :: caused by :: FieldPath field names may not start with '$'.

1 Answer 1

7

You need to iterate the loop of photos array and replace the extension,

  • $map to iterate loop of photos array
  • $replaceOne to replace extension
db.users.updateMany(
  { photos: { $regex: ".png" } },
  [{
    $set: {
      photos: {
        $map: {
          input: "$photos",
          in: {
            $replaceOne: {
              input: "$$this",
              find: ".png",
              replacement: ".jpg"
            }
          }
        }
      }
    }
  }]
)

Playground

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

Comments

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.