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.
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.
After a bit of research I found this solution to work for me:
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)}})})