In the previous screens, we have established our collections and indexed them for efficient data retrieval. Now, we delve into the fundamentals of querying methods that make our database useful. For targeted data retrieval, we need to implement a find
method in our database.
The find
method is the basis of querying our document-oriented database. It checks each document in a specified collection against specified criteria, which is a dictionary where the key is the field we want to match and the value is the value we're matching against.
In the example provided, we define a 'products' collection containing documents that represent different fruits. We utilize the find
method to extract fruits of a particular color. In the financial world, this is equivalent to querying all the transactions belonging to a particular party or of a specific type.
These 'simple queries', as they're often called in MongoDB, form the basis of our data retrieval logic. However, we can also implement more advanced querying tools such as sorting and filtering, which we will discuss later on.
To career-oriented data scientists and AI developers dealing with complex and large datasets, efficient data retrieval methods like this can be the key to successful and speedy data analysis.
xxxxxxxxxx
if __name__ == "__main__":
class DocumentDB:
def __init__(self):
self.collections = {}
def find(self, collection, criteria):
if collection not in self.collections:
return None
results = []
for document in self.collections[collection]:
match = True
for field, value in criteria.items():
if document[field] != value:
match = False
break
if match:
results.append(document)
return results
db = DocumentDB()
db.collections['products'] = [
{'name': 'apple', 'color': 'red', 'price': 1.2},
{'name': 'banana', 'color': 'yellow', 'price': 0.5},
]
print(db.find('products', {'color': 'red'}))