Update all records in mongodb

Recently we discovered a problem in Be My Eyes where an id was not unique.
So we needed a quick fix to make all ids a forthrunning unique number before solving the problem in the code.

On stackoverflow i found this question:
http://stackoverflow.com/questions/4146452/mongodb-what-is-the-fastest-way-to-update-all-records-in-a-collection

And I modified the code to work for our schema.
Please note: the code in the question was working, but slow for many millions records (a problem we don't have yet ;-).

var cnt = 1;
db.users.find().forEach(function(data) {
    db.users.update({_id:data._id},{$set:{id2:cnt}});
    cnt++;
});

So I simply loop over all users and assign a new value to id2. The value is a counter I maintain.
By default the update only updates one document, if you need more than one document to be updated, just send in the parameter.

For more info on update please refer to the mongodb documentation on update.

Please beware that with very large collections, this will be slow.

Of course, this is run in the mongo shell.

Image courtesey of https://www.flickr.com/photos/sukiweb/

comments powered by Disqus