MongoDB script to stamp a counter to existing documents.


Sometimes you may get a situation where you want to stamp counter values to existing documents. You can use the following script to so that.
In this example script, I am going to stamp userId which is a number starting from 1 to n

var counter = 0;
db.getCollection('users').find({}).sort({email: 1}).forEach(function(rec){
    counter++;
    rec.userId = counter;
    db.getCollection('users').save(rec);
})