python 用于连接和读取mongodb数据到pandas df的函数

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了python 用于连接和读取mongodb数据到pandas df的函数相关的知识,希望对你有一定的参考价值。

import pandas as pd
from pymongo import MongoClient 

# set connection with mongodb
def _connect_mongo(host, port, username, password, db):
    """ A util for making a connection to mongo """

    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]

# read mongodb collection and move to pandas dataframe
def read_mongo(db, collection, query={}, host='localhost', port=27017, username=None, password=None, no_id=True):
    """ Read from Mongo and Store into DataFrame """

    # Connect to MongoDB
    db = _connect_mongo(host=host, port=port, username=username, password=password, db=db)

    # Make a query to the specific DB and Collection
    cursor = db[collection].find(query)

    # Expand the cursor and construct the DataFrame
    df =  pd.DataFrame(list(cursor))

    # Delete the _id
    if no_id:
        del df['_id']

    return df

以上是关于python 用于连接和读取mongodb数据到pandas df的函数的主要内容,如果未能解决你的问题,请参考以下文章

python-pandas读取mongodb读取csv文件

Python爬虫数据保存到MongoDB中

Springboot连接NoSQL数据库MongoDB,读取集合数据文档

Springboot连接NoSQL数据库MongoDB,读取集合数据文档

Excel用Python读取清洗后怎么写入数据

flink实时读取mongodb方案调研-实现mongodb cdc