Bootstrap
之前在MongoDB中有大量数据要分析,需要导入到Pandas中进行分析,本文就主要分享一下我将MongoDB中数据导入到Pandas的代码。

1、Python中操作MongoDB

Python使用MongoDB数据库,需要用到pymongo库

1)安装pymongo库

pip install pymongo

2)安装完后查看

pip list

3)模块引用

import pymongo

4)通过Pymongo与MongoDB建立连接

import pymongo
from pymongo import MongoClient
client = MongoClient('localhost',27017)

2、导出读取MongoDB数据到Pandas的代码

import pandas as pd
from pymongo import MongoClient
def _connect_mongo(host, port, username, password, db):
    """ 指定帐户和密码建立连接 """
    if username and password:
        mongo_uri = 'mongodb://%s:%s@%s:%s/%s' % (username, password, host, port, db)
        conn = MongoClient(mongo_uri)
    else:
        conn = MongoClient(host, port)
    return conn[db]
def read_mongo(db, collection, query={}, host='localhost', port=27017, username=None, password=None, no_id=True):
    """ 从Mongo读取并存储到DataFrame """
    #连接MongoDB
    db = _connect_mongo(host=host, port=port, username=username, password=password, db=db)
    #对特定的数据库和集合进行查询
    cursor = db[collection].find(query)
    #读取数据并构造DataFrame
    df =  pd.DataFrame(list(cursor))
    #删除MongoDB中主键_id
    if no_id:
        del df['_id']
    return df