1

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 Answer 1

0

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)}})})
Sign up to request clarification or add additional context in comments.

1 Comment

Same answer as already provided here: stackoverflow.com/questions/59690531/… Use BulkWrite as stated in that answer to avoid unnecessary multiple DB update calls

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.