Skip to content

Instantly share code, notes, and snippets.

@eindiran
Created February 26, 2020 20:33
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save eindiran/529a6b14b2029254d9b3313de3ac5638 to your computer and use it in GitHub Desktop.
Save eindiran/529a6b14b2029254d9b3313de3ac5638 to your computer and use it in GitHub Desktop.
A context manager to handle a MongoDB Collection
'''
A context manager for handling a PyMongo driver MongoDB connection
to access a collection.
'''
from contextlib import contextmanager
from pymongo import MongoClient
import traceback
@contextmanager
def mongo_collection(uri: str, timeout_ms: int, collection: str, db_name=None):
'''Open up a MongoDB connection, grab a db, then get a collection.'''
try:
mongo_client = MongoClient(uri, timeout_ms)
if db_name is not None:
db = mongo_client[db_name]
else:
db = mongo_client.get_default_database()
yield db.get_collection(collection)
except BaseException as err:
traceback.print_exc()
finally:
mongo_client.close()
# Example:
# with mongo_collection(uri, 1000, collection) as c:
# results = c.find_all('{foo.bar}')
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment