0

Is there a easier way to update field text in mongodb globally?

I don't have a mongodb knowledge but some thing like this,

Update "all collections that has field1" set field1=some where field1=1234

Please take a look at mysql solution using db dumps: Similar to Find and replace in entire mysql database

If the above is not possible what is the best way to go about writing a one time script to migrate data in mongodb? This is in linux environment.

Community
  • 1
  • 1
srs
  • 516
  • 1
  • 4
  • 20
  • 1
    Do you want to set the field to the same value in all documents of the collection or is it something more complex? Please be precise in describing what you want to do. Vague questions might give you vague answers. – Philipp Sep 26 '15 at 23:14
  • Thanks for looking at it, I edited for clarity. – srs Sep 27 '15 at 14:37

1 Answers1

2

To update multiple documents in the same collection, use the multi:true option when you do an update:

db.collection.update(
   { "field1": 1234 },
   { "$set": { "field1" : somevalue } },
   { multi: true }
);

MongoDB has no commands which affect more than one collection at a time, so you will have to execute this for every collection separately. When you want to do this in the shell, you can perform the command on every collection separately with a script like this:

 db.getCollectionNames().forEach( function(name) {
      db[name].update(
             { "field1": 1234 },
             { "$set": { "field1" : somevalue } },
             { multi: true }
      );
 });
Philipp
  • 67,764
  • 9
  • 118
  • 153