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

我错过了什么?


当前回答

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

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

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

查看如何导入视频

其他回答

使用:

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

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

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

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

查看如何导入视频

我在mongoimport shell上使用这个

mongoimport --db db_name --collection collection_name --type csv --file C:\\Your_file_path\target_file.csv --headerline

类型可以选择csv/tsv/json 但是只有csv/tsv可以使用——headerline

你可以阅读更多的官方文件。

如果您有多个文件,并且希望使用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)

当我试图导入CSV文件时,我得到了一个错误。我所做的。 首先,我用大写字母更改了标题行的列名,并删除了“-”,并在需要时添加了“_”。然后输入下面的命令导入CSV到mongo

$ mongoimport --db=database_name --collection=collection_name --type=csv --file=file_name.csv --headerline