Skip to content

Instantly share code, notes, and snippets.

@TroublesNCuddles
Created March 8, 2020 23:37
Show Gist options
  • Save TroublesNCuddles/fc5716c5ee2509e5918ffdad40f7e3e6 to your computer and use it in GitHub Desktop.
Save TroublesNCuddles/fc5716c5ee2509e5918ffdad40f7e3e6 to your computer and use it in GitHub Desktop.
const {MongoClient} = require('mongodb');
const MONGODB_URI = 'mongodb://localhost:27017/KoalatyEconomy';
const LOWEST_NUMBER = '0000000';
const MAX_NUMBER = 9999999;
const MAX_BATCH_SIZE = 98000;
const AREA_CODES = [420, 469];
const generateNumbers = (area_codes) => {
let numbers = [];
for (let index = 0; index < area_codes.length; index++) {
area_codes[index] = parseInt(`${area_codes[index]}${LOWEST_NUMBER}`);
}
for (let count = 0; (count + parseInt(LOWEST_NUMBER)) < MAX_NUMBER; count++) {
area_codes.forEach(code => {
numbers.push(code + count);
});
}
return numbers;
};
const shuffle = (array) => {
for (let i = array.length - 1; i > 0; i--) {
let j = Math.floor(Math.random() * (i + 1));
[array[i], array[j]] = [array[j], array[i]];
}
};
const connect = async () => {
return await MongoClient.connect(MONGODB_URI, {
useNewUrlParser: true,
useUnifiedTopology: true
});
};
connect()
.then(async mongodb_client => {
let numbers = generateNumbers(AREA_CODES);
let run = true;
console.log(numbers.length.toLocaleString() + ' generated...');
shuffle(numbers);
try {
const collection = mongodb_client.db().collection('phone_numbers');
let c = 1;
await collection.createIndex({number: 1}, {unique: true});
await collection.createIndex({assigned: 1});
while (run) {
let batch = numbers.slice(0, MAX_BATCH_SIZE);
numbers = numbers.slice(MAX_BATCH_SIZE);
if (batch.length === 0) {
run = false;
continue;
}
console.log(`Inserting batch #${c} [${batch.length.toLocaleString()}]. Approximately ${Math.ceil(numbers.length / MAX_BATCH_SIZE)} batches left...`);
for (let index = 0; index < batch.length; index++) {
batch[index] = {number: batch[index], assigned: false};
}
console.time(`Batch #${c} completed...`);
await collection.insertMany(batch);
console.timeEnd(`Batch #${c} completed...`);
c++;
}
} finally {
await mongodb_client.close();
}
})
.catch(error => {
console.log(error);
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment