Adam K Dean

Update all values in a MongoDB collection to a random range

Published on 22 January 2020 at 16:49 by Adam

The following query allows you to easily update all values in a collection of documents to a random number range, in this case, between 50 and 100.

db.collection.find({}).forEach(function(doc) {
  db.collection.update({ _id: doc._id }, { 
    $set: { value: Math.floor(Math.random() * (100 - 50 + 1)) + 50 }
  })
})

Note: I haven't tested this on a large data set. This is more of a snippet for future me.



This post was first published on 22 January 2020 at 16:49. It was filed under archive with tags mongodb, snippet.