How to use mongoimport to import csv How to use mongoimport to import csv database database

How to use mongoimport to import csv


Your example worked for me with MongoDB 1.6.3 and 1.7.3. Example below was for 1.7.3. Are you using an older version of MongoDB?

$ cat > locations.csvName,Address,City,State,ZIPJane Doe,123 Main St,Whereverville,CA,90210John Doe,555 Broadway Ave,New York,NY,10010 ctrl-d$ mongoimport -d mydb -c things --type csv --file locations.csv --headerlineconnected to: 127.0.0.1imported 3 objects$ mongoMongoDB shell version: 1.7.3connecting to: test> use mydbswitched to db mydb> db.things.find(){ "_id" : ObjectId("4d32a36ed63d057130c08fca"), "Name" : "Jane Doe", "Address" : "123 Main St", "City" : "Whereverville", "State" : "CA", "ZIP" : 90210 }{ "_id" : ObjectId("4d32a36ed63d057130c08fcb"), "Name" : "John Doe", "Address" : "555 Broadway Ave", "City" : "New York", "State" : "NY", "ZIP" : 10010 }


I was perplexed with a similar problem where mongoimport did not give me an error but would report importing 0 records. I had saved my file that didn't work using the OSX Excel for Mac 2011 version using the default "Save as.." "xls as csv" without specifying "Windows Comma Separated(.csv)" format specifically. After researching this site and trying the "Save As again using "Windows Comma Separated (.csv)" format, mongoimport worked fine. I think mongoimport expects a newline character on each line and the default Mac Excel 2011 csv export didn't provide that character at the end of each line.


We need to execute the following command:

mongoimport --host=127.0.0.1 -d database_name -c collection_name --type csv --file csv_location --headerline

-d is database name

-c is collection name

--headerline If using --type csv or --type tsv, uses the first line as field names. Otherwise, mongoimport will import the first line as a distinct document.

For more information: mongoimport