‘’’
要求:
将数据集1的数据通过python插入到MongoDB数据库中
1)数据库名字为: crawl_one;
2)集合名字为: collection_one;
3)数据文件为: movie_world.csv;
‘’’
import pymongo, csv
class MongoDate():
def __init__(self, name):
self.client = pymongo.MongoClient() # 若为本地mongo可以省略括号里的参数(host,port)
self.db = self.client['crawl_one'][name]
def read_data(self, filename):
with open(filename, encoding="utf-8") as f:
f_csv = csv.DictReader(f) # 调用DictReader()方法,可以把csv直接转成为字典
for row in f_csv:
self.add_one(row) # 调用add_one() 写入方法来将每行的数据写入mongo数据库中
def add_one(self, data):
result = self.db.insert_one(data)
print(result)
if __name__ == '__main__':
md = MongoDate('collection_one')
md.read_data('movie_world.csv')
附csv:
mongo截个图