DEV Community

Cover image for Update all values in a MongoDB collection to a random range
Adam K Dean
Adam K Dean

Posted on

Update all values in a MongoDB collection to a random range

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 }
  })
})
Enter fullscreen mode Exit fullscreen mode

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

Top comments (0)