Skip to content

Instantly share code, notes, and snippets.

@ro6ley
Created January 28, 2020 13:59
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save ro6ley/1973fc35ff7be544b96f06d7df3a3081 to your computer and use it in GitHub Desktop.
Save ro6ley/1973fc35ff7be544b96f06d7df3a3081 to your computer and use it in GitHub Desktop.
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