包含联系方式的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 -d db_name -c collection_name --type csv --file filename.csv --headerline --host hostname:portnumber --authenticationDatabase admin --username 'iamauser' --password 'pwd123'

其他回答

如果您在生产环境中工作,则很可能需要进行身份验证。您可以使用类似的方法对具有适当凭证的正确数据库进行身份验证。

mongoimport -d db_name -c collection_name --type csv --file filename.csv --headerline --host hostname:portnumber --authenticationDatabase admin --username 'iamauser' --password 'pwd123'

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

我的需求是导入.csv(没有标题)到远程MongoDB实例。对于mongoimport v3.0.7,以下命令适用于我:

mongoimport -h <host>:<port> -u <db-user> -p <db-password>  -d <database-name> -c <collection-name> --file <csv file location> --fields <name of the columns(comma seperated) in csv> --type csv

例如:

mongoimport -h 1234.mlab.com:61486 -u arpitaggarwal -p password  -d my-database -c employees --file employees.csv --fields name,email --type csv

下面是导入后的截图:

其中姓名和电子邮件是.csv文件中的列。

给定.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名称。

以上这些答案都很棒。这也是开发一个功能齐全的应用程序的方法。

但是如果你想要快速创建原型,想要在集合不断变化时保持灵活性,以及最小化你早期的代码库,有一种更简单的方法,但很少讨论。

你现在基本上可以放弃蒙古进口了。如果在这里提到这个问题,我可以节省3个小时。让我分享给大家:

Mongodb有一个名为Mongo Compass的GUI,它有csv和json导入功能,只需点击即可开箱即用。它是Mongo生态系统的正式组成部分。在撰写本文时,它是免费的,并且非常适合我的用例。 https://www.mongodb.com/products/compass

You simply get MongoDB compass running on your machine by following the simple installation. A couple of fields for DB connection and authentication directly in the GUI. Import the csv/json file. It took less than a second on a 30KB file to be parsed before user (me) validates. Validate the "type" of each property. Great feature, I could directly mention the property types such as booleans, integers, etc. In my experience, they seem all default to string. You can update before importing. Dates were more finicky and needed special attention on the coding side. One click further the csv is a collection in your mongo db local or on the cloud. Voila!