python 把json数据导入mongodb数据库

1、构造df数据,并导入数据库

from MongoDbHandler import MongoDbHandler
from pandas import DataFrame

        finallyResult = {}
        finallyResult["aa"]="bb"
        finallyResult["cc"]="dd"
        df = DataFrame(finallyResult,index=[1])
        data = df.to_dict('records')
        mongoSession = MongoDbHandler('A','B', 'C')#A为mongodb的name,B为用户名,C为密码
        mongoSession.insert_many("D", "E", data)#D为数据库名,E为集合名
        time.sleep(2)
        mongoSession.close()

2、上面代码用到的函数,脚本如下

# coding=utf-8

from pymongo import MongoClient
import pandas as pd

class MongoDbHandler(object):
    def __init__(self, ip, user=None, keyword=None):
        if user == None or keyword == None:
            URL = 'mongodb://{0}'.format(ip)
        else:
            URL = 'mongodb://{0}:{1}@{2}'.format(user, keyword, ip)
            print user,keyword
        print URL
        self.__Client = MongoClient(URL)

    def find_all(self, db, collection, condition = None):
        self.__db = self.__Client[db]
        self.__collection = self.__db[collection]
        cursor = self.__collection.find(condition)
        result = []
        for contentDict in cursor:
            result.append(contentDict)
        return result

    def find_all_cursor(self, db, collection, condition = None):
        self.__db = self.__Client[db]
        self.__collection = self.__db[collection]
        cursor = self.__collection.find(condition)
        return cursor

    def insert_one(self, db, collection, jsonData):
        _db = self.__Client[db]
        _collection = _db[collection]
        result = _collection.insert_one(jsonData)

    def insert_many(self, db, collection, jsonData):
        _db = self.__Client[db]
        _collection = _db[collection]
        result = _collection.insert_many(jsonData)
        return result

    def drop(self,db,collection):
        _db = self.__Client[db]
        _collection = _db[collection]
        _collection.drop()
    def close(self):
        return self.__Client.close()
  • 0
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值