Export mongodb collection data and import it back using node js
This code will read the documents from the MongoDB collection (the export functionality) and then writes to a file as JSON. This file is used to read (the import functionality) and insert the JSON into another collection. The code uses MongoDB NodeJS driver.
The Export:
Reads from the collection inCollection
based upon a supplied query, and writes to a file as JSON "out_file.json".
const MongoClient = require('mongodb').MongoClient;const fs = require('fs');const dbName = 'testDB';const client = new MongoClient('mongodb://localhost:27017', { useUnifiedTopology:true });client.connect(function(err) { //assert.equal(null, err); console.log('Connected successfully to server'); const db = client.db(dbName); getDocuments(db, function(docs) { console.log('Closing connection.'); client.close(); // Write to file try { fs.writeFileSync('out_file.json', JSON.stringify(docs)); console.log('Done writing to file.'); } catch(err) { console.log('Error writing to file', err) } });}const getDocuments = function(db, callback) { const query = { }; // this is your query criteria db.collection("inCollection") .find(query) .toArray(function(err, result) { if (err) throw err; callback(result); }); };
The Import:
Reads the exported "out_file.json" file and inserts the JSON data in to the outCollection
.
client.connect(function(err) { const db = client.db(dbName); const data = fs.readFileSync('out_file.json'); const docs = JSON.parse(data.toString()); db.collection('outCollection') .insertMany(docs, function(err, result) { if (err) throw err; console.log('Inserted docs:', result.insertedCount); client.close(); });});