Skip to content

Instantly share code, notes, and snippets.

@mieitza
Forked from wixb50/mongo_to_csv.py
Created January 3, 2018 15:09
Show Gist options
  • Star 21 You must be signed in to star a gist
  • Fork 9 You must be signed in to fork a gist
  • Save mieitza/5d35d0a4f2671127f7120c75c8764385 to your computer and use it in GitHub Desktop.
Save mieitza/5d35d0a4f2671127f7120c75c8764385 to your computer and use it in GitHub Desktop.
python mongo to csv use pandas.
# @Author: xiewenqian <int>
# @Date: 2016-11-28T20:35:09+08:00
# @Email: wixb50@gmail.com
# @Last modified by: int
# @Last modified time: 2016-12-01T19:32:48+08:00
import pandas as pd
from pymongo import MongoClient
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]
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 and '_id' in df:
del df['_id']
return df
if __name__ == '__main__':
df = read_mongo('db_test', 'db_collection', {}, '172.168.203.174', 10800)
df.to_csv('1.csv', index=False)
@jevy146
Copy link

jevy146 commented Aug 27, 2021

如果数据的数据量20多个G内存还可以运行的动吗

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment