Guest User

Untitled

a guest
Apr 20th, 2018
100
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.09 KB | None | 0 0
  1. {
  2. "_id" : ObjectId("5ad0ade0bef1fc2fba99489d"),
  3. "property_a" : 0.0,
  4. "property_b" : 0.0,
  5. "property_c" : 0.0,
  6. "property_d" : 0.0,
  7. "property_e" : 0.0,
  8. .....
  9.  
  10. }
  11.  
  12. import pandas as pd
  13. from pymongo import MongoClient
  14.  
  15.  
  16. def _connect_mongo(host, port, username, password, db):
  17. """ A util for making a connection to mongo """
  18.  
  19. if username and password:
  20. mongo_uri = 'mongodb://%s:%s@%s:%s/%s' % (username, password, host, port, db)
  21. conn = MongoClient(mongo_uri)
  22. else:
  23. conn = MongoClient(host, port)
  24.  
  25.  
  26. return conn[db]
  27.  
  28.  
  29. def read_mongo(db, collection, query={}, host='localhost', port=27017, username=None, password=None, no_id=True):
  30. """ Read from Mongo and Store into DataFrame """
  31.  
  32. # Connect to MongoDB
  33. db = _connect_mongo(host=host, port=port, username=username, password=password, db=db)
  34.  
  35. # Make a query to the specific DB and Collection
  36. cursor = db[collection].find(query)
  37.  
  38. # Expand the cursor and construct the DataFrame
  39. df = pd.DataFrame(list(cursor))
  40.  
  41. # Delete the _id
  42. if no_id:
  43. del df['_id']
  44.  
  45. return df
Add Comment
Please, Sign In to add comment