5

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!

Community
  • 1
  • 1
Ender phan
  • 185
  • 2
  • 3
  • 10

3 Answers3

7

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() 
    } 
  ) 
}
sergiuz
  • 5,353
  • 1
  • 35
  • 51
  • Thank you for your help. Seem this is decent function to work on with. But, I'm still confused in the "name" part. If I want to create a list of string and the its name gonna be generated by those string, it could be pleasant more than the "name1, name2, name3...."? @Sergiu Zaharie – Ender phan Nov 03 '16 at 11:49
  • You can generate ransom strings, take a look http://stackoverflow.com/questions/1349404/generate-random-string-characters-in-javascript – sergiuz Nov 03 '16 at 12:04
3

Best way will be read off docs about random generate in mongodb. https://docs.mongodb.com/v2.6/tutorial/generate-test-data/ Also you could use special service for generate random data. For example: https://www.mockaroo.com/

Rider_BY
  • 1,129
  • 1
  • 13
  • 31
  • Thank you so much. It's kindda useful to me. :) @Rider_BY. Do we have able to create a function to do this stuff?. If we could do it, do we still have to insert one by one for its name and birthday? – Ender phan Nov 03 '16 at 11:01
3

I have try mgeneratejs, very easy to use, mgeneratejs

here is sample command, mgeneratejs print data to stdout, then use mongoimport import these data into mongod:

mongodb-osx-x86_64-4.0.1 $ mgeneratejs '{"name": "$name", "age": "$age", "emails": {"$array": {"of": "$email", "number": 3}}}' -n 5 | mongoimport --uri mongodb://localhost:27017/test --collection user --mode insert
2018-08-09T16:19:13.295+0800    connected to: localhost
2018-08-09T16:19:14.544+0800    imported 5 documents
mahengyang
  • 289
  • 2
  • 16