Skip to content

Instantly share code, notes, and snippets.

@mishbah
Created September 5, 2024 00:27
Show Gist options
  • Save mishbah/4713b2572f3ee536259de2cf7dbc2ca9 to your computer and use it in GitHub Desktop.
Save mishbah/4713b2572f3ee536259de2cf7dbc2ca9 to your computer and use it in GitHub Desktop.
Simpan method ini di ~/.mongoshrc.js
function copyCollections(
sourceDbName,
collectionNames = [],
targetDbName = "tenant_operation",
batchSize = 1000
) {
const sourceDb = db.getSiblingDB(sourceDbName);
const targetDb = db.getSiblingDB(targetDbName);
for (const collectionName of collectionNames) {
targetDb.getCollection(collectionName).drop();
let totalMoved = 0;
const cursor = sourceDb.getCollection(collectionName).find();
while (cursor.hasNext()) {
const batch = [];
// Mengambil batch dokumen
for (let i = 0; i < batchSize && cursor.hasNext(); i++) {
batch.push(cursor.next());
}
if (batch.length > 0) {
targetDb.getCollection(collectionName).insertMany(batch);
totalMoved += batch.length;
print(`Copy ${batch.length} documents... Total copied: ${totalMoved}`);
}
}
print(
`Successfully copied a total of ${totalMoved} documents from ${sourceDbName}.${collectionName} to ${targetDbName}.${collectionName}.`
);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment