Advertisement
Guest User

Untitled

a guest
Jul 3rd, 2017
66
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 0.99 KB | None | 0 0
  1. import pandas as pd
  2. from pymongo import MongoClient
  3.  
  4. # set connection with mongodb
  5. def _connect_mongo(host, port, username, password, db):
  6. """ A util for making a connection to mongo """
  7.  
  8. if username and password:
  9. mongo_uri = 'mongodb://%s:%s@%s:%s/%s' % (username, password, host, port, db)
  10. conn = MongoClient(mongo_uri)
  11. else:
  12. conn = MongoClient(host, port)
  13.  
  14.  
  15. return conn[db]
  16.  
  17. # read mongodb collection and move to pandas dataframe
  18. def read_mongo(db, collection, query={}, host='localhost', port=27017, username=None, password=None, no_id=True):
  19. """ Read from Mongo and Store into DataFrame """
  20.  
  21. # Connect to MongoDB
  22. db = _connect_mongo(host=host, port=port, username=username, password=password, db=db)
  23.  
  24. # Make a query to the specific DB and Collection
  25. cursor = db[collection].find(query)
  26.  
  27. # Expand the cursor and construct the DataFrame
  28. df = pd.DataFrame(list(cursor))
  29.  
  30. # Delete the _id
  31. if no_id:
  32. del df['_id']
  33.  
  34. return df
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement