Skip to content

Instantly share code, notes, and snippets.

@brydavis
Last active August 27, 2019 17:34
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 brydavis/1355b2ac852e86f6b7efec073cb7d789 to your computer and use it in GitHub Desktop.
Save brydavis/1355b2ac852e86f6b7efec073cb7d789 to your computer and use it in GitHub Desktop.
Using a context manager to work with Mongo
from pymongo import MongoClient
# https://medium.com/@ramojol/python-context-managers-and-the-with-statement-8f53d4d9f87
class MongoDBConnection(object):
"""MongoDB Connection"""
def __init__(self, host='localhost', port='27017'):
self.host = f"mongodb://{host}:{port}"
self.connection = None
def __enter__(self):
self.connection = MongoClient(self.host)
return self
def __exit__(self, exc_type, exc_val, exc_tb):
self.connection.close()
# docker container run --name mongo -p 27017:27017 -d mongo mongod
with MongoDBConnection() as mongo:
conn = mongo.connection
db = conn.my_app
collection = db.people
# clear the deck
collection.delete_many({})
# insert data
collection.insert_many([
{
"first_name": "Lisetta",
"last_name": "Bennitt",
"email": "lbennitt0@typepad.com"
}, {
"first_name": "Maurits",
"last_name": "Trazzi",
"email": "mtrazzi1@mysql.com"
}, {
"first_name": "Mandel",
"last_name": "Handover",
"email": "mhandover2@weebly.com"
}
])
# find person
person = collection.find({"first_name":"Mandel"})
pprint(list(person))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment