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

其他回答

分享给未来的读者:

在本例中,我们需要添加host参数以使其工作

mongoimport -h mongodb://someMongoDBhostUrl:somePORTrunningMongoDB/someDB -d someDB -c someCollection -u someUserName -p somePassword --file someCSVFile.csv --type csv --headerline --host=127.0.0.1

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

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

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

首先你应该跳出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$

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