欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

Python访问MongoDB,并且转换成Dataframe的方法

程序员文章站 2022-05-28 21:22:27
如下所示: #!/usr/bin/env python # -*- coding: utf-8 -*- # @time : 2018/7/13 11:10...

如下所示:

#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @time : 2018/7/13 11:10
# @author : baoshan
# @site : 
# @file : pandans_pymongo.py
# @software: pycharm community edition

import pymongo
import pandas as pd


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 = pymongo.mongoclient(mongo_uri)
 else:
  conn = pymongo.mongoclient(host, port)

 return conn[db]


def read_mongo(db, collection, query={}, host='test43', 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).limit(10)

 # expand the cursor and construct the dataframe
 df = pd.dataframe(list(cursor))
 df.to_csv("abc.csv", encoding="utf_8_sig") # 处理中文乱码问题

 if no_id:
  del df['_id']

 return df


read_mongo(db='service', collection='trace_log_regular', query={}, host='xxx', port=27017, username="xxx", password="xxx")

小结:

1. 解决了pymongo访问mongodb的问题

2. 解决了查询的数据转成dataframe的问题

3. 解决了dataframe写入到csv的问题

4. 解决了中文乱码问题。

以上这篇python访问mongodb,并且转换成dataframe的方法就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持。