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.
Asked
Active
Viewed 365 times
1

fIwJlxSzApHEZIl
- 11,861
- 6
- 62
- 71
1 Answers
0
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)}})})

fIwJlxSzApHEZIl
- 11,861
- 6
- 62
- 71
-
***Same answer as already provided here:*** https://stackoverflow.com/questions/59690531/update-many-fields-in-mongodb-with-random-values/59692501#comment130135555_59692501 ***Use BulkWrite as stated in that answer to avoid unnecessary multiple DB update calls*** – whoami - fakeFaceTrueSoul Oct 19 '22 at 14:40