Search
 
SCRIPT & CODE EXAMPLE
 
CODE EXAMPLE FOR JAVASCRIPT

nodejs export all mongodb collections

const MongoClient = require('mongodb').MongoClient;
const fs = require('fs');
const dbName = 'database1';
const client = new MongoClient('db_url', {useUnifiedTopology:true,useNewUrlParser: true, });

client.connect(function(err) {
  console.log('Connected successfully to server');
  const db = client.db(dbName);
  var collections = [ 'collection1', 'collection2' ];
  collections.forEach(async collection => {
    var documents =  await getDocuments(db, collection);
    try {
      // Write files outside of server directory
      // prevents app restarts on nodemon
      fs.writeFile("../"+collection+'.json', JSON.stringify(docus), err => {
      });
      console.log('Done writing to file.');
    } catch (err) { 
      console.log('Error writing to file', err)
    }
  })
});

async function getDocuments(db, collection) {
  return await db.collection(collection).find({}).toArray()
};
 
PREVIOUS NEXT
Tagged: #nodejs #export #mongodb #collections
ADD COMMENT
Topic
Name
6+1 =