通过执行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()


Logo

为开发者提供学习成长、分享交流、生态实践、资源工具等服务,帮助开发者快速成长。

更多推荐