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 """
db
= _connect_mongo
(host
=host
, port
=port
, username
=username
, password
=password
, db
=db
)
cursor
= db
[collection
].find
(query
)
df
= pd
.DataFrame
(list(cursor
))
if no_id
:
del df
['_id']
return df
if __name__
== '__main__':
db
= 'database'
collection
= 'tb'
host
= 'localhost'
df
= read_mongo
(db
, collection
, query
={}, host
=host
, port
=27017, username
=None, password
=None, no_id
=True)
print(df
)
转载请注明原文地址: https://mac.8miu.com/read-513637.html