Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to create huge random document in MongoDB

I am newbie with MongoDB. I'm trying to create a database which will be included 10,000 data. The data will contain "username" and "Birthday".

I want to create 10,000 data with random username and birthday. Do we have a fastest way to create this kind of database?.

Thank you so much for your help!

like image 915
Ender phan Avatar asked Dec 24 '22 23:12

Ender phan


1 Answers

Here are some functions that will help you to create a random string(name) and random date since 1950 untill 2000 and insert it into mongodb.

function getRandomInt(min, max) {
    return Math.floor(Math.random() * (max - min + 1)) + min;
}

function getRandomDate() {
    // aprox nr of days since 1970 untill 2000: 30years * 365 days
    var nr_days1 = 30*365;
    // aprox nr of days since 1950 untill 1970: 20years * 365 days
    var nr_days2 = -20*365;

    // milliseconds in one day
    var one_day=1000*60*60*24

    // get a random number of days passed between 1950 and 2000
    var days = getRandomInt(nr_days2, nr_days1);

    return new Date(days*one_day)
}

for (var i = 1; i <= 10000; i++) {    
  db.test.insert( 
    { 
      name : "name"+i, 
      birthday: getRandomDate() 
    } 
  ) 
}
like image 163
sergiuz Avatar answered Jan 12 '23 12:01

sergiuz