Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 685
Dia Sarkar Avatar asked Aug 31 '15 09:08

Dia Sarkar


People also ask

How do I export a MongoDB collection to CSV?

Export MongoDB to CSV (e.g. Excel) Open the Export Wizard and select your export source. This screen only appears if you haven't chosen an item in the Connection Tree, run a previous query, or selected specific documents. Next, choose CSV as the export format then click Next.

How do I get data from MongoDB collection using node JS?

To select data from a collection in MongoDB, we can use the findOne() method. The findOne() method returns the first occurrence in the selection. The first parameter of the findOne() method is a query object.

How do I export a collection from MongoDB?

So, to export data from the MongoDB database, MongoDB provides a command-line tool known as mongoexport. Using this tool you can exports data of a collection in JSON or CSV(comma-separated value) format. Moreover, we can also use features like limit and sort on a collection while exporting the data.


1 Answers

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

like image 87
Hiren S. Avatar answered Oct 08 '22 19:10

Hiren S.