Export and Import data from collection in mongodb using nodejs

I am new to mongodb so need some help with export and import of mongodb data with nodejs.I have a mongodb database and some collections(eg product collection,formula collection and rules collection which have reference of product id) inside it, I want to export the data from different collections based on params of api request and generate file containing the corresponding data this file will be downloaded on client browser. The exported file can be used by the user to import exported data into another db instance.Have already searched on this topic and came acros this answer not sure if i can use mongoexport for my task. Any idea how can i do that.

I have also asked on stackoverflow: node.js - Export mongodb collection data and import it back using node js - Stack Overflow

Any help or idea is greatly appreciated.

Thanks
Yogesh

for importing and exporting the data form database, mongodb provides import & export clause. check this out.
Here is the code for exporting the collections:

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 file “out_file.json” and inserts the JSON data into 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();
    });
});
1 Like