Skip to content

Instantly share code, notes, and snippets.

@seozed
Last active May 9, 2022 10:04
Show Gist options
  • Save seozed/0c92d3b16b1447a844cfbad5836909fe to your computer and use it in GitHub Desktop.
Save seozed/0c92d3b16b1447a844cfbad5836909fe to your computer and use it in GitHub Desktop.
MongoDbConnection
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