包含联系方式的CSV文件:

Name,Address,City,State,ZIP  
Jane Doe,123 Main St,Whereverville,CA,90210  
John Doe,555 Broadway Ave,New York,NY,10010 

运行这个不会向数据库添加文档:

$ mongoimport -d mydb -c things --type csv --file locations.csv --headerline

Trace说导入了1个对象,但是在MongoDB shell中运行db.things.find()不会显示任何新文档。

我错过了什么?


当前回答

检查文件末尾是否有空行,否则在某些版本的mongoimport上最后一行将被忽略

其他回答

给定.csv文件,我只有一个列,没有标题,下面的命令对我有用:

mongoimport -h <mongodb-host>:<mongodb-port> -u <username> -p <password> -d <mongodb-database-name> -c <collection-name> --file file.csv --fields <field-name> --type csv

其中field-name指的是.csv文件中列的Header名称。

奇怪的是,没有人提到——uri flag:

mongoimport --uri connectionString -c questions --type csv --file questions.csv --headerline 

分享给未来的读者:

在本例中,我们需要添加host参数以使其工作

mongoimport -h mongodb://someMongoDBhostUrl:somePORTrunningMongoDB/someDB -d someDB -c someCollection -u someUserName -p somePassword --file someCSVFile.csv --type csv --headerline --host=127.0.0.1

我们需要执行以下命令:

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

-d是数据库名称 -c是集合名 如果使用——type csv或——type tsv,则使用第一行作为字段名。否则,mongoimport将第一行作为一个单独的文档导入。

欲了解更多信息:mongoimport

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.