Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
A simple script to showcase PyMongo usage in vanilla Python.
from pymongo import MongoClient
# create a MongoDB client
client = MongoClient('localhost', 27017)
series_db = client['SeriesDB']
series_collection = series_db['series']
def insert_document(collection, data):
""" Function to insert a document into a collection and
return the document's id.
"""
return collection.insert_one(data).inserted_id
def find_document(collection, elements, multiple=False):
""" Function to retrieve a single or multiple documents from a provided
collection using a dictionary containing a document's elements.
"""
if multiple:
results = collection.find(elements)
return [r for r in results]
else:
return collection.find_one(elements)
def update_document(collection, query_elements, new_values):
""" Function to update a single document in a collection.
"""
return collection.update_one(query_elements, {'$set': new_values})
def delete_document(collection, query):
""" Function to delete a single document from a collection.
"""
collection.delete_one(query)
# insert a new show and get its _id
new_show = {
"name": "FRIENDS",
"year": 1995
}
id_ = insert_document(series_collection, new_show)
# retrieve a show
result = find_document(series_collection, {'name': 'FRIENDS'}, True)
print(result)
# update the show
update_document(series_collection, {'_id': id_}, {'name': 'F.R.I.E.N.D.S'}))
result = find_document(series_collection, {'_id': id_})
print(result)
# delete a show
delete_document(series_collection, {'_id': id_})
result = find_document(series_collection, {'_id': id_})
print(result)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment