Being able to retrieve a single document is useful but often, we will want to fetch multiple documents based on some condition. For this, we typically use a query
method. This is where our document database starts to shine - as the flexibility of a JSON-like structure allows us to easily query nested attributes.
For any senior engineer working in software development, you might have come across querying data when dealing with programs related to AI or finance, or any system that needs to fetch data based on specific conditions. For our document database, a basic query operation will sift through every single document it has stored, checking to see if the document matches the given condition.
Let's illustrate this with a query operation that retrieves all documents where the key customer_id
is equal to 12345
. See the Python code in the code
section.
xxxxxxxxxx
def query_document(db, key, value):
result = []
for id, document in db.items():
if document.get(key) == value:
result.append(document)
return result
if __name__ == '__main__':
db = {
'order1': { 'customer_id': 12345, 'product': 'Book' },
'order2': { 'customer_id': 12346, 'product': 'Shirt' },
'order3': { 'customer_id': 12345, 'product': 'Shoes' }
}
#Query the database
print(query_document(db, 'customer_id', 12345))