Created
March 27, 2023 10:04
-
-
Save l-portet/7c62a603ef42d5f3f15f325920eaf058 to your computer and use it in GitHub Desktop.
Dump a mongo collection
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
import 'dotenv/config'; | |
import fs from 'fs'; | |
import path from 'path'; | |
import { fileURLToPath } from 'url'; | |
import { MongoClient } from 'mongodb'; | |
const DB_NAME = ''; | |
const COLLECTION_NAME = ''; | |
const __filename = fileURLToPath(import.meta.url); | |
const __dirname = path.dirname(__filename); | |
function createSnapshotFile() { | |
const now = Date.now(); | |
const dumpDir = path.join(__dirname, './dump'); | |
const fileName = `snapshot-${now}.json`; | |
const filePath = path.join(dumpDir, fileName); | |
if (!fs.existsSync(dumpDir)) { | |
fs.mkdirSync(dumpDir); | |
} | |
const stream = fs.createWriteStream(filePath, { flags: 'a' }); | |
stream.write('['); | |
return stream; | |
} | |
(async () => { | |
const stream = createSnapshotFile(); | |
const url = process.env.DATABASE_URL; | |
const mongo = new MongoClient(url); | |
await mongo.connect(); | |
console.log('Connected to DB'); | |
const db = mongo.db(DB_NAME); | |
const collection = db.collection(COLLECTION_NAME); | |
const cursor = collection.find({}); | |
const length = await collection.countDocuments(); | |
let index = 0; | |
for await (const record of cursor) { | |
const sep = index === length - 1 ? '' : ','; | |
console.log(`dumping ${record._id} (${index + 1}/${length})`); | |
stream.write(JSON.stringify(record) + sep); | |
index++; | |
} | |
stream.write(']'); | |
stream.end(); | |
await mongo.close(); | |
console.log('Done!'); | |
})(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment