Skip to content

Instantly share code, notes, and snippets.

@waptik
Created September 11, 2020 02:29
Show Gist options
  • Save waptik/d6f64af9b4d69271b47c0021812d4f7a to your computer and use it in GitHub Desktop.
Save waptik/d6f64af9b4d69271b47c0021812d4f7a to your computer and use it in GitHub Desktop.
Export mongodb collection data and import it back using node js
// credit link: @https://stackoverflow.com/questions/63573995/export-mongodb-collection-data-and-import-it-back-using-node-js
const fs = require('fs');
const dbName = 'testDB';
const client = new MongoClient('mongodb://localhost:27017', { useUnifiedTopology:true });
// function to export db document
function exportDbCollection(){
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);
});
};
}
// function to import db collection
function importDBCollection() {
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();
});
});
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment