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

其他回答

如果您有多个文件,并且希望使用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(没有标题)到远程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文件中的列。

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 }

我们需要执行以下命令:

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天后,我终于靠自己做到了。感谢所有支持我的用户。