JuanDa237
JuanDa237

Reputation: 376

How to update values in string array in all documents? - MongoDB

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 😁

Upvotes: 0

Views: 99

Answers (1)

mohammad Naimi
mohammad Naimi

Reputation: 2359

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

Upvotes: 1

Related Questions