How to export data in .csv file in MongoDB?

Connect with

MongoDBWell, when you encounter to export your data to a file like .csv. In first time in your life, you might think how to export dta into .csv file in MongoDB? but believe me this is very simple. Exporting of data is one step process in mongoDB. exporting can be with different utility tool but I’m demonstrating here by command line argument.

Exporting of mongoDB data in .csv file

On command line type or copy following line and change respective parameter values according to your need.

syntax:

mongoexport -d dbName -c collectionName --type=csv --fields fieldsNameWithCommaSeparated -q 'mongoDBquery' --out /pathOfYourChoice/csvFileName.csv

Example as follow:

mongoexport -d myServiceDB -c myDeviceDetails --type=csv --fields mobileno,name -q '{"city":"/Delhi/"}' --out /tmp/myFileName.csv

Explanation of Argument of mongoexport tool

Here, I’m trying to explain each arguments, which I provided above.

  • mongoexport
  • : this is a utility tool in mongoDB under the ../bin/ directory , which is being used to export the data in either .csv or .json format and same exported data can be imported by using mongoimport utility tool.

  • -d myServiceDB
  • : here -d followed by name of the database , where your collection reside.

  • -c myDeviceDetails
  • -c followed by name of your collection from which you want to export your data in either .csv or .json format.

  • --type=csv
  • –type=csv means , exported data format in .csv not in .json. default is .json format.

  • --fields mobileno,name
  • –fields followed by name of the fields which you want to include in .csv file, here fields are comma (,) separated.

  • -q '{"city":"/Delhi/"}'
  • : provide the mongoDB query for which data need to export. Query is optional here , if you not provide query, export all data for provided collection.

  • --out /tmp/myFileName.csv
  • : provide the name of file with absolute location, where you want to generate exported data in .csv format.

Your comments are welcome to improve this post.


Connect with

Leave a Reply

Your email address will not be published. Required fields are marked *