6

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

1
  • 3
    Please tell me you just did not post your account credentials to StackOverflow. You need to change those quickly. Commented Aug 31, 2015 at 9:19

2 Answers 2

6

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);
        }
    })
Sign up to request clarification or add additional context in comments.

Comments

5

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

1 Comment

@narainsagar Yes. Worked with 1000000 records.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.