Dia Sarkar
Dia Sarkar

Reputation: 313

Export mongodb collection data to csv file in node js

I have created a mongodb collection in mongolab and want to print all documents in that collecton. I have mongolab and the url of mongolab to get connected with the collection is -

mongodb://user:[email protected]:41248/new

The sample document structure is -

{
    "_id": "9759572745-Sing",

   "details": {
    "Gender": "M",
    "PreTrainingStatus": "Fresher",
    "Religion": "Hindu",
    "attendanceInPercentage": "",
    "batchHolders": {
        "AssessmentDate": "Thu Jul 16 2015",
        "CourseFee": "7500",
        "isEditable": false
    },
    "batchID": "282726",
    "eid": "",
    "whereDidYouHearAboutStar": "---Select---",
    "skillInstructorOrTrainerName": "282726",
    "specificGovtInstitutetieups": "---Select---",
    "isSelected": false,
    "isEditable": false
},
"addedOnMs": 1439455766000,
"submittedOnMs": 1439454813000,
"latitude": "27.409566879272",
"longitude": "77.69295501709",
"locationName": "Uttar Pradesh 281006,null"
}

I want to Print it and all nested properties to be displayed in a column. But I am not able to do so, Please help.

Thank you (In Advance), Dia

Upvotes: 6

Views: 16548

Answers (2)

Manoj Khatri
Manoj Khatri

Reputation: 674

Implementing json2csv library for exporting data to csv file on nodejs

Example

const json2csv = require('json2csv').parse;

//For unique file name
const dateTime = new Date().toISOString().slice(-24).replace(/\D/g, 
'').slice(0, 14); 

const filePath = path.join(__dirname, "../../../", "public", "exports", "csv-" + dateTime + ".csv");

let csv; 

const student = await req.db.collection('Student').find({}).toArray();

// Logging student
// [{id:1,name:"John",country:"USA"},{id:1,name:"Ronny",country:"Germany"}]

const fields = ['id','name','country'];

 try {
        csv = json2csv(booking_info, {fields});
    } catch (err) {
        return res.status(500).json({err});
    }

 fs.writeFile(filePath, csv, function (err) {
        if (err) {
            return res.json(err).status(500);
        }
        else {
            setTimeout(function () {
                fs.unlink(filePath, function (err) { // delete this file after 30 seconds
                if (err) {
                    console.error(err);
                }
                console.log('File has been Deleted');
            });

        }, 30000);
            res.download(filePath);
        }
    })

Upvotes: 6

Hiren S.
Hiren S.

Reputation: 2832

You can use https://www.npmjs.com/package/json2csv

Set nested option value to true

And Also Specify fields that you want from JSON. For nested document you can specify like this details.Gender

Upvotes: 5

Related Questions