Created
September 5, 2014 21:31
-
-
Save jobsamuel/6e77967481b8cba7d4d9 to your computer and use it in GitHub Desktop.
Playing with MongoDB - Inserting documents
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
////////////////////////////// | |
// Playing with MongoDB ///// | |
// 1 - Inserting documents / | |
/////////////////////////// | |
// MongoDB Driver module. | |
var MongoClient = require('mongodb').MongoClient | |
// Set the name of the database you want to connect with. | |
, database = "college"; | |
MongoClient.connect('mongodb://localhost:27017/' + database, function(err, db) { | |
if(err) throw err; | |
// Set the number of docs you want to insert. | |
var n = 1000; | |
for (var i = 0; i<n; i++) { | |
var temp = 0 | |
, careers = ["Engineering", "Medicine", "Marketing", "Design", "Education", "Laws"] | |
, langs = ["EN", "POR", "ES", "FRA", "ITA", "GER"] | |
, first_names = [ | |
["John", "Brian", "Robert", "Tim", "Aaron", "Noah", "Ian", "Nathan", "Ethan", "Michael", "James", "Daniel", "Willian", "Dylan", "Matthew", "Jack", "Justin", "Brandon", "Adam", "Harry"], | |
["Karen", "Monica", "Rose", "Cindy", "Chloe", "Emily", "Jennifer", "Jessica", "Zoe", "Ellie", "Paige", "Taylor", "Lucy", "Katie", "Sarah", "Mia", "Vanessa", "Amber", "Sophia", "Emma"] | |
] | |
, last_names = ["Smith", "Brown", "Jones", "Miller", "Davis", "Williams", "Lee", "Thompson", "Taylor", "Walker", "Robinson", "Carter", "Evans", "Allen", "Adams", "Baker", "Harris", "Clark", "Scott", "Johansson"] | |
, genders = ["Male", "Female"] | |
, gender = Math.round(Math.random()*1) | |
, phone = "55" + Math.round(Math.random()*9) + "-" + Math.round(Math.random()*9) + "7" + Math.round(Math.random()*9) + "3" | |
, doc = { | |
student: i, | |
personal_info: { | |
name: first_names[gender][Math.round(Math.random()*19)] + " " + last_names[Math.round(Math.random()*19)], | |
gender: genders[gender], | |
phone: phone, | |
email: "student_" + i + "@university.edu" | |
}, | |
career: careers[Math.round(Math.random()*5)], | |
language: langs[Math.round(Math.random()*5)], | |
grades: { | |
year1: Math.random()*100, | |
year2: Math.random()*100, | |
year3: Math.random()*100, | |
year4: Math.random()*100 | |
} | |
}; | |
db.collection('students').insert(doc, function(err, record) { | |
if(err) throw err; | |
// Count the number of document inserted in the database. | |
temp += Object.keys(record).length; | |
// When the temp reach the n value, it will close the database safely. | |
if (temp >= n) { | |
console.log(temp + " files were successfully inserted!"); | |
db.close(); | |
} | |
}); | |
} | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment