0

I have in my collection this structure:

{
    _id: ObjectId('...'),
    images: [
        "images/key1",
        "images/key2",
        "images/key3",
        "images/key4"
    ],
    .... ,
    ....
}

So, I want to update all documents to:

{
    _id: ObjectId('...'),
    images: [
        "key1",
        "key2",
        "key3",
        "key4"
    ],
    .... ,
    ....
}

Replacing in all values 'images/' with ''. Thanks 😁

1 Answer 1

1

you could done it with update aggregation like this first match the doc and then in project use map and them split and choose last element

db.collection.update({},
[
  {
    $addFields: {
      images: {
        $map: {
          input: "$images",
          as: "i",
          in: {
            $last: {
              $split: [
                "$$i",
                "images/"
              ]
            }
          }
        }
      }
    }
  }
],{multi:true})

https://mongoplayground.net/p/6fDBAlpKDBj

or use this

db.collection.update({},
[
  {
    $addFields: {
      images: {
        $map: {
          input: "$images",
          as: "i",
          in: {
            $arrayElemAt: [
              {
                $split: [
                  "$$i",
                  "images/"
                ]
              },
              1
            ]
          }
        }
      }
    }
  }
],{multi:true})

replace $last with $arrayelementAt https://mongoplayground.net/p/ecHMquZGazy

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

14 Comments

I get an error that say: Unrecognized expression '$last'. Do you know what is happening?
I split item of images and it will convert to array , and $last means put last element of array
did you see my playground ?
Yes, it worked!. but when i use it in my db i get that error.
could you provide your code ?
|

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.