How to set a random string value to all documents in a mongodb collection with the mongo shell?

Viewed 17

I need to set a randomly generated string property on all values in a MongoDB collection. I'd like to use the mongo shell and the updateMany function in order to quickly and easily achieve this.

1 Answers

After a bit of research I found this solution to work for me:

  1. Copy and paste this function into your mongo shell:
function makeid(length) {
    var result           = '';
    var characters       = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
    var charactersLength = characters.length;
    for ( var i = 0; i < length; i++ ) {
      result += characters.charAt(Math.floor(Math.random() * 
 charactersLength));
   }
   return result;
}

console.log(makeid(5));
  1. Verify it works in your mongo shell by typing makeid(6)

  2. Call the function on every document to set a unique randomly generated property:

db.collectionName.find({}).forEach(function(myDocument) {db.collectionName.update({_id: myDocument._id}, {$set: { randomId: makeid(6)}})})
Related