Jul 11, 2016

Import/Export .CSV file in MongoDB

We can import .csv data in mongodb using mongoimport, please see following example.


Without authentication

mongoimport --db <DBNAME> --collection <COLLECTION_NAME> --type csv --headerline --file  /path/to/Import.csv

--db : here we have to give database name.
--collection: here we have to give Collection name.
--type: file type like csv, json etc.
--file: Path of file will be import into mongodb.
--headerline: It means first row is field name.

With authentication

mongoimport –<host_ip> --port 27012 --username <user> --password <pass> --collection <collection_name>--db <db_name>--file <file path>

Example: Suppose we have a csv file which contains data of Employee like NAME, ADDRESS, PHONE etc. And we have to import data in mongodb.

Run the following command

>mongoimport --db TEST1 --collection myCol --type csv --headerline --file  D:/MDB/Import.csv



We can export mongodb data in csv using mongoexport.


mongoexport --db <users> --collection <Collection_Name> --type=csv --fieldFile fields.txt --out /opt/backups/contacts.csv

Example: Now above imported data going to export using following command.

{ "_id" : ObjectId("57834347fbe91e1b53e67dca"), "NAME" : "Dilip", "ADDRESS" : "Delhi", "PHONE" : NumberLong(9018878876) }
{ "_id" : ObjectId("57834348fbe91e1b53e67dcb"), "NAME" : "Vipul", "ADDRESS" : "Ghazibad", "PHONE" : NumberLong(4444499870) }
{ "_id" : ObjectId("57834348fbe91e1b53e67dcc"), "NAME" : "Swati", "ADDRESS" : "Noda", "PHONE" : NumberLong(8998009986) }

We can export the above data into csv file to run the following command.

mongoexport --db TEST1 --collection myCol --csv --fields NAME,ADDRESS,PHONE --out D:/MDB/Export.csv


Exported csv data