Guest User

Untitled

a guest
Mar 19th, 2018
118
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.57 KB | None | 0 0
  1. #!/usr/bin/python3
  2. """ Demonstration of PyMongo usage. """
  3.  
  4. from bson.objectid import ObjectId
  5. from datetime import datetime
  6. from pymongo import MongoClient
  7.  
  8. __author__ = "@ivanleoncz"
  9.  
  10.  
  11. class Connector:
  12. """ MongoDB connector and jobs: login, add session and delete session. """
  13.  
  14. def connect(self):
  15. """ Configuring MongoDB client. """
  16. db_user = "mongo"
  17. db_pass = "mongo"
  18. db_addr = "127.0.0.1:27017"
  19. uri = "mongodb://{0}:{1}@{2}".format(db_user,db_pass,db_addr)
  20. client = MongoClient(uri,serverSelectionTimeoutMS=6000)
  21. return client
  22.  
  23.  
  24. def add_record(self):
  25. """ Adding record. """
  26. client = self.connect()
  27. db = client.new_database
  28. collection = db.new_collection
  29. # database and collection are created, at the moment that the query is performed
  30. result = collection.insert_one({"Username":"alan.turing","Country":"England",
  31. "Birthdate":"06-23-1912","Died":"06-07-1954",
  32. "Record":datetime.now()})
  33. data = self.find_record(result.inserted_id)
  34. return data
  35.  
  36.  
  37. def find_record(self, obj_id):
  38. """ Verifying existence of Object ID. """
  39. client = self.connect()
  40. db = client.new_database
  41. collection = db.new_collection
  42. result = collection.find_one({"_id":ObjectId(obj_id)})
  43. return result
  44.  
  45.  
  46. if __name__ == "__main__":
  47. db = Connector()
  48. result = db.add_record()
  49. if len(result) != 0:
  50. print("Record successfully added!")
  51. else:
  52. print("Record not found!")
Add Comment
Please, Sign In to add comment