本文簡述了如何通過python將json文件導(dǎo)入到mongodb數(shù)據(jù)庫
# -*- 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('04tencent_hr.json', 'r')
# 創(chuàng)建mongodb客戶端
self.client = MongoClient(self.host, self.port)
# 創(chuàng)建數(shù)據(jù)庫
self.db = self.client.tencent
# 創(chuàng)建集合
self.collection = self.db.jobs
# 關(guān)閉文件
def __close_file(self):
self.file.close()
# 寫入數(shù)據(jù)庫
def write_database(self):
self.__open_file()
# 轉(zhuǎn)換為python對象
data = json.load(self.file)
try:
self.collection.insert(data)
print '寫入成功'
except Exception as e:
print e
finally:
self.__close_file()
if __name__ == '__main__':
j2m = JsonToMongo()
j2m.write_database()