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
After a bit of research I found this solution to work for me:
- 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));
Verify it works in your mongo shell by typing
makeid(6)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)}})})
1 Comment
whoami - fakeFaceTrueSoul
Same answer as already provided here: stackoverflow.com/questions/59690531/… Use BulkWrite as stated in that answer to avoid unnecessary multiple DB update calls