‘’’
    要求:
    将数据集1的数据通过python插入到MongoDB数据库中
    1)数据库名字为: crawl_one;
    2)集合名字为: collection_one;
    3)数据文件为: movie_world.csv;
    ‘’’

    1. import pymongo, csv
    2. class MongoDate():
    3. def __init__(self, name):
    4. self.client = pymongo.MongoClient() # 若为本地mongo可以省略括号里的参数(host,port)
    5. self.db = self.client['crawl_one'][name]
    6. def read_data(self, filename):
    7. with open(filename, encoding="utf-8") as f:
    8. f_csv = csv.DictReader(f) # 调用DictReader()方法,可以把csv直接转成为字典
    9. for row in f_csv:
    10. self.add_one(row) # 调用add_one() 写入方法来将每行的数据写入mongo数据库中
    11. def add_one(self, data):
    12. result = self.db.insert_one(data)
    13. print(result)
    14. if __name__ == '__main__':
    15. md = MongoDate('collection_one')
    16. md.read_data('movie_world.csv')

    附csv:
    a1.png
    mongo截个图
    a2.png