Stefano php, milano

Import Many Csv Files In Mongo

Use this one liner to bulk import all the csv files inside a given directory into the mydatabase db in Mongo.

for i in *.csv; do mongoimport -d mydatabase -c ${i%.*} --type csv --file $i --headerline ; done

The files should be plain CSV files with an header row (that is: the first line should contain the fields name). Each file will be put into a different collection named after the filename.

For example, the following CSV file addressbook.csv:

id,name,email
1,Tommy,tommy@example.com

Will create an addressbook collection with the following object:

{
    _id   : 'xxxxxxxxxxxxxxxxx',
    id    : 1,
    name  : "Tommy",
    email : "tommy@example.com"
}

Enjoy!

Tags: mongodb