包含联系方式的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()不会显示任何新文档。

我错过了什么?


当前回答

如果您有多个文件,并且希望使用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上最后一行将被忽略

我们需要执行以下命令:

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.4版本,请使用以下语法:

mongoimport -u "username" -p "password" -d "test" -c "collections" --type csv --file myCsv.csv --headerline

3天后,我终于靠自己做到了。感谢所有支持我的用户。

首先你应该跳出mongo shell,然后像这样执行mongoimport命令:

Manojs-MacBook-Air:bin Aditya$ mongoimport -d marketdata -c minibars 
--type csv 
--headerline
--file '/Users/Aditya/Downloads/mstf.csv'

2017-05-13T20:00:41.989+0800    connected to: localhost
2017-05-13T20:00:44.123+0800    imported 97609 documents
Manojs-MacBook-Air:bin Aditya$

罗伯特·斯图尔特的回答很好。

我想补充的是,你也可以输入你的字段——columHaveTypes和——字段像这样:

mongoimport -d myDb -c myCollection --type csv --file myCsv.csv 
  --columnsHaveTypes --fields "label.string(),code.string(),aBoolean.boolean()"

(注意字段之间的逗号后不要有空格)

对于其他类型,请参阅doc: https://docs.mongodb.com/manual/reference/program/mongoimport/#cmdoption-mongoimport-columnshavetypes