Last active
August 27, 2019 17:34
-
-
Save brydavis/1355b2ac852e86f6b7efec073cb7d789 to your computer and use it in GitHub Desktop.
Using a context manager to work with Mongo
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 | |
# 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