5

I would like to prepend a string to all values of a mongo collection's column.

Something like

 db.testcoll.update({},{$set:{column1 : "prependstring"+ column1}});

Is there something like this ?

thegrid
  • 509
  • 1
  • 6
  • 20
  • You will need to retrieve, modify, and update each document. You can use the aggregation framework as explained in an answer below, but it will produce a new set of documents, not modify the old. You can use the `$out` stage to save the new documents to a new collection. – wdberkeley Dec 15 '14 at 17:34

1 Answers1

5

That can be achieved using the $concat operator in an aggregation pipeline.

db.testcoll.aggregate([{
  $project: {
    column1: {
      $concat: ['prependstring', '$column1']
    }
  }
}]);

As specified in the official MongoDB docs (here) the $concat operator only works with strings.

Alp
  • 29,274
  • 27
  • 120
  • 198
vladzam
  • 5,462
  • 6
  • 30
  • 36
  • 1
    You will also need to project all of the other fields in the document to get output documents that look like the originals. The aggregation pipeline creates new documents from old, do you will need to use `$out` to save to a new collection. – wdberkeley Dec 15 '14 at 17:34
  • @wdberkeley Indeed. In order to permanently change the collection, the $out stage must be specified, together with the name of the output collection – vladzam Dec 15 '14 at 18:33