Last active
March 10, 2018 14:25
-
-
Save ivanleoncz/8af6e6bf00586e1c2589137db2c45b20 to your computer and use it in GitHub Desktop.
Demonstration of PyMongo usage (MongoDB 3.4.3 + PyMongo 3.4.0).
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/python3 | |
""" Demonstration of PyMongo usage. """ | |
from bson.objectid import ObjectId | |
from datetime import datetime | |
from pymongo import MongoClient | |
__author__ = "@ivanleoncz" | |
class Connector: | |
""" MongoDB connector and jobs: login, add session and delete session. """ | |
def connect(self): | |
""" Configuring MongoDB client. """ | |
db_user = "mongo" | |
db_pass = "mongo" | |
db_addr = "127.0.0.1:27017" | |
uri = "mongodb://{0}:{1}@{2}".format(db_user,db_pass,db_addr) | |
client = MongoClient(uri,serverSelectionTimeoutMS=6000) | |
return client | |
def add_record(self): | |
""" Adding record. """ | |
client = self.connect() | |
db = client.new_database | |
collection = db.new_collection | |
# database and collection are created, at the moment that the query is performed | |
result = collection.insert_one({"Username":"alan.turing","Country":"England", | |
"Birthdate":"06-23-1912","Died":"06-07-1954", | |
"Record":datetime.now()}) | |
data = self.find_record(result.inserted_id) | |
return data | |
def find_record(self, obj_id): | |
""" Verifying existence of Object ID. """ | |
client = self.connect() | |
db = client.new_database | |
collection = db.new_collection | |
result = collection.find_one({"_id":ObjectId(obj_id)}) | |
return result | |
if __name__ == "__main__": | |
db = Connector() | |
result = db.add_record() | |
if len(result) != 0: | |
print("Record successfully added!") | |
else: | |
print("Record not found!") | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment