通过执行python代码将json文件导入MongoDB中
通过执行python代码将json文件导入MongoDB中,我这里的json数据大概有35M左右,运行代码需要几分钟才能插入完。1.集成环境:pycharm,python版本3.72.需要在pycharm中绑定localhost MongoDB,建议去官网下载MongoDB,下载过程中勾选MongoDB compass方便可视化查看数据。具体怎么在pycharm中绑定MongoDB可以自行查找。3
·
通过执行python代码将json文件导入MongoDB中,我这里的json数据大概有35M左右,运行代码需要几分钟才能插入完。
1.集成环境:pycharm,python版本3.7
2.需要在pycharm中绑定localhost MongoDB,建议去官网下载MongoDB,下载过程中勾选MongoDB compass方便可视化查看数据。具体怎么在pycharm中绑定MongoDB可以自行查找。
3.执行代码
1)json数据集:
2)代码成功后:
3)在pycharm中查看MongoDB数据
4)在MongoDB compass中查看数据
程序代码
# -*- coding:utf-8 -*-
from pymongo import *
import json
class JsonToMongo(object):
def __init__(self):
self.host = 'localhost'
self.port = 27017
# 读取json文件
def __open_file(self):
self.file = open('sample.json', 'r',encoding='utf-8') #encoding='utf-8'加上,不然可能会出现编码报错
# 创建mongodb客户端
self.client = MongoClient(self.host, self.port)
# 创建数据库
self.db = self.client.ceshi
# 创建集合
self.collection = self.db.jsonFile
# 关闭文件
def __close_file(self):
self.file.close()
# 写入数据库
def write_database(self):
self.__open_file()
tmp = []
for line in open('./sample.json', 'r',encoding='utf-8'):
tmp.append(json.loads(line)) #tmp的类型为list
data = tmp
'''
#这里酌情修改,因为我json中的数据中的字典有条数据是:"_id":{"$oid":"5699b8cea98063e18e9ae636"}
而MongoDB不支持带有$的"$oid",我这里将json中的全部"$oid"变为'oid'
'''
for item in data:
li = item['_id']
li['oid'] = li['$oid']
del li['$oid']
item['_id']=li #上面的代码是去掉$号,如果json数据没有$号则执行self.collection.insert_one(item)这一句代码就可以
self.collection.insert_one(item) #依次遍历数据库,插入数据
try:
# self.collection.insert_one(item)
print('写入成功')
except Exception as e:
print(e)
finally:
self.__close_file()
if __name__ == '__main__':
j2m = JsonToMongo()
j2m.write_database()
更多推荐
已为社区贡献1条内容
所有评论(0)