TW80000 TW80000 - 2 months ago 12
Javascript Question

MongoDB: Update a string field in all documents

I have a MongoDB database with many documents in a collection. Each of those articles has a field called

myField
containing a string.

Is it possible for me to run a bulk update on all documents in the collection, modifying the value of
myField
for each document?


In my case I just want to strip off a trailing ".html" from each of the fields. I'm using node.js to interact with Mongo in my application but I'd prefer to be able to run a single command on the
mongo
command prompt to do this update if that's possible.

Answer

Yest it possible to update mongoDB document information from command prompt using mongo.

say script file name migration.js and go to this file directory and open command prompt and run this command.

mongo localhost/dbName migration.js

and migration.js code like:

print('Please wait it may will take some time to complete migration');
print('....');

db.collectionName.find().forEach( function(doc) {

    if(!doc._id) {
        print('No doc found');
        return;
    }
    // if need can apply logic to update myField

    db.collectionName.update({_id: doc._id}, {$set: {myField: "newVale"}});
});

print('Migration has been completed :)');
Comments