Last active
May 9, 2022 10:04
-
-
Save seozed/0c92d3b16b1447a844cfbad5836909fe to your computer and use it in GitHub Desktop.
MongoDbConnection
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
from pymongo import MongoClient | |
class MongoDBConnection(object): | |
"""MongoDB Connection""" | |
def __init__(self, host='localhost', port=27017): | |
self.host = host | |
self.port = port | |
self.connection = None | |
def __enter__(self): | |
self.connection = MongoClient(self.host, self.port) | |
return self | |
def __exit__(self, exc_type, exc_val, exc_tb): | |
self.connection.close() | |
if __name__ == '__main__': | |
mongo = MongoDBConnection() | |
with mongo: | |
collection = mongo.connection.MyDbName.Customers | |
customer = collection.find({'_id': 123}) | |
print(customer.get('name')) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment