Mongodb – CSV file restore in mongodb

mongodb

Export MySql data in following command.

SELECT id,documentfile
FROM documentuploads
INTO OUTFILE '/home/home2/agri_doc.csv'
FIELDS TERMINATED BY ','
ENCLOSED BY '"'
LINES TERMINATED BY '\n';

CSV file data

"3","%PDF-1.7\
%����\
1 0 obj\
<<\
/Type /Catalog\
/Pages 2 0 R\
>>\"

I am currently using mongodb shell version v3.6.3. i want to import my csv file in mongo database, and I have created a collection documentupload where only two field id, docs. data is latin1_swedish_ci encoded. I tried following command.

mongorestore -d agrilicense2 -c documentupload  --type csv --file /home/shiva/home/agri_doc3.csv  --fields id, docs --headerline

Show output
error parsing command line options: unknown option "type"
Thank you

Best Answer

You can import the (.csv) file through the following commands

mongoimport -d databaseName -c collectionName --type csv --file locationsOftheCSVFile.csv --headerline

For example here I have created the database name test and collection name StackExchange and going to import the LocarionReq.csv file.

> use test
switched to db test
> db.createCollection("StackExchange");
{ "ok" : 1 }
> show collections
StackExchange

C:\Program Files\MongoDB\Server\4.0\bin>mongoimport -d test -c StackExchange --type csv --file C:\test\LocationReq.csv --headerline
2019-04-11T10:58:53.147+0300    connected to: localhost
2019-04-11T10:58:53.263+0300    imported 1000 documents

Now you can check the total document records through the mongo shell command

>db.StackExchange.find().count();
 1000

If you want to find the document records through mongo shell then run the command such as

> db.StackExchange.find().pretty(); -- an easy-to-read attractive format.

Or

> db.StackExchange.find();

Note : Run mongoimport or mongoexport from the system command line, not the mongo shell.

For your further ref here