How can I prepend a string to every value in an array in Mongoose?

Viewed 43

Say I have a collection of documents like this...

{ name: "Bob", listIDs: ["1c2f", "32a1", "0ebf"] }
{ name: "Meg", listIDs: ["a844", "8132", "b246"] }
...

How might I prepend the string "0000" to every value in listIDs for every document? e.g.

{ name: "Bob", listIDs: ["00001c2f", "000032a1", "00000ebf"] }
{ name: "Meg", listIDs: ["0000a844", "00008132", "0000b246"] }
...
1 Answers

You can try update with aggregation pipeline starting from MongoDB 4.2,

  • $map to iterate loop of listIDs array
  • $concat to concat 0000 with element value
db.collection.updateMany({},
  [{
    $set: {
      listIDs: {
        $map: {
          input: "$listIDs",
          in: { $concat: ["0000", "$$this"] }
        }
      }
    }
  }]
)

Playground

Related