In this section, we will cover the creation of our Document Database Class. Assuming your intermediate programming knowledge and experience, you should be familiar with Object-Oriented Programming (OOP). In OOP, a class is like a blueprint for creating objects. For our database, the objects will be the documents we want to store.
In Python, we begin the class definition with the keyword class
followed by the class name. In our case, it would be DocumentDB
representing our Document-Oriented Database. The class will have methods for creating, deleting and modifying key-value pairs, just like our documents.
The __init__
method is used to initialize attributes. We will use a Python dictionary, denoted as docs
, to store our documents. This is similar to a Hashmap in Java or an Object in JavaScript.
Our class will have theadd_doc
, delete_doc
and modify_doc
methods, representing the basic CRUD operations(CReate, Update, Delete). Crud operations are fundamental in any persistent storage system. You can think of these operations as similar to trading stocks in finance - adding a document is like buying a stock, deleting a document is like selling, and modifying a document would be adjusting your positions.
The add_doc
method will require a key and a value, it will store these as a key-value pair in the docs
dictionary. The delete_doc
method will remove the key-value pair associated with its given key, and modify_doc
will replace the value of a key-value pair corresponding to its given key.
These methods will, for now, perform these operations in-memory meaning that changes will be lost at the end of the program execution. However, we will look at ways to persist these changes in a later section.
xxxxxxxxxx
class DocumentDB:
def __init__(self):
self.docs = {}
def add_doc(self, key, value):
self.docs[key] = value
def delete_doc(self, key):
if key in self.docs:
del self.docs[key]
def modify_doc(self, key, value):
if key in self.docs:
self.docs[key] = value
if __name__ == "__main__":
db = DocumentDB()
db.add_doc('1', 'Hello World')
print(db.docs)
db.modify_doc('1', 'Hello Algodaily')
print(db.docs)
db.delete_doc('1')
print(db.docs)