Java Programming Tutorials

Java programming tutorials with many code examples!

How to generate random test data in MongoDB

A common problem when starting with MongoDB is how to generate random test data in MongoDB. A large data set is especially needed for MongoDB performance tuning.

Function to generate random ISODate

This simple function returns an ISODate from within last 24 hours. You can extend it to return dates from other date ranges:

var day = 1000 * 60 * 60 * 24;
var randomDate = function () {
  return new Date(Date.now() - (Math.floor(Math.random() * day)));
}

When executed it returns random ISODate() as expected:

> new Date()
ISODate("2017-04-09T19:36:43.417Z")
> randomDate()
ISODate("2017-04-09T06:43:24.249Z")

Function to generate random name/string

Another helpful function, this time to generate, for example, names of users:

var randomName = function() {
  // Base 36 uses letters and digits to represent a number:
  return (Math.random()+1).toString(36).substring(2);
}

And here it’s results:

> randomName()
rj611nxjre

How to insert 1.000.000 random documents

Now we can use the following loop to insert pseudo-random documents into MongoDB:

for (var i = 1; i <= 1000000; ++i) {
  db.test.insert({
      name: randomName(),
      creationDate: randomDate(),
      uid: i
  });
}

On my laptop it took about 10 minutes to insert 1 million of random documents.

> for (var i = 1; i <= 1000000; ++i) {
    var randomName = (Math.random()+1).toString(36).substring(2);
    db.test.insert({name: randomName, creationDate: randomDate(), uid: i});
  }
... ... ... WriteResult({ "nInserted" : 1 })
> db.test.count()
1000000

A sample, generated MongoDB document looks like this:

{
        "_id" : ObjectId("58ea8976733313ff20cfc9e3"),
        "name" : "caed7zs2f6",
        "creationDate" : ISODate("2017-04-09T07:31:47.422Z"),
        "uid" : 1
}

Have fun! :-)

References:

Share with the World!