包含联系方式的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 --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

其他回答

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

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

你现在基本上可以放弃蒙古进口了。如果在这里提到这个问题,我可以节省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!

使用:

mongoimport -d 'database_name' -c 'collection_name' --type csv --headerline --file filepath/file_name.csv

如果您有多个文件,并且希望使用python导入所有文件,您可以执行以下操作。

import os
import subprocess

# directory of files
dir_files = 'C:\data'
# create list of all files
_, _, fns = next(os.walk(dir_files))
files = [os.path.join(dir_files, fn) for fn in fns]
# mongotool address
mongotool = r'C:\Program Files\MongoDB\Server\4.4\bin\mongoimport.exe'
# name of mongodb database
mydatabase = 'mydatabase'
# name of mongodb collection
mycollection = 'mycollection'
# import all files to mongodb
for fl in files:
    commands =[mongotool, '--db', mydatabase,
               '--collection', mycollection,
               '--file', fl,
               '--type', 'tsv',
               '--headerline']
    subprocess.Popen(commands, shell=True)

mongoimport -d test -c test——type csv——file SampleCSVFile_119kb.csv——headerline .csv

检查采集数据:—

var collections = db.getCollectionNames(); For (var I = 0;我< collections.length;我+ +) { print('Collection: ' + collections[i]); //打印每个集合的名称 db.getCollection(集合[我]);().forEach (printjson); //然后打印每个元素的json }

Robert Stewart已经回答了如何用mongoimport导入。

我建议用3T MongoChef工具(3.2+版本)简单地导入CSV。也许将来能帮到别人。

你只需要选择集合 选择要导入的文件 您还可以取消选择将要导入的数据。还有很多选择。 收集进口

查看如何导入视频