Why MongoDB?
Today's modern applications are typically hosted in the cloud and need to be highly scalable and available. Traditional RDBMS databases such as MS-SQL, MySQL, and Postgres struggle to scale horizontally and often fail to meet the demands of these applications, even when configured for synchronization. In contrast, NoSQL databases are schema-less and primarily document-based (e.g., JSON), making it easier to create replicas and distribute datasets.
According to the CAP Theorem, a distributed system can only guarantee two out of the three following properties: Consistency (C), Availability (A), and Partition Tolerance (P).
First, why should we care about NOSQL data modeling, how is it different from relational database modeling, and how do we express relationships in MongoDB, a document database?
In relational databases, we use normalization to avoid redundant data and JOIN queries to reference data from other tables. In NoSQL databases, data modeling involves two main approaches: embedding and referencing.
We use embedding when we have the following requirements:
1. One-to-One relationship
2. One-to-Few relationship
3. Embedded data changes infrequently and is bounded (does not grow)
4. Data will be queried and updated together
We use referencing when:
1. One-to-Many relationships exist
2. Many-to-Many relationships exist
3. Related documents or data are queried or updated independently or frequently
4. The data is unbounded (grows infinitely)
A good example of referencing is the relationship between patients and appointments. In this case, we do not know how many appointments a patient will have in their lifetime. Another example is blog posts and comments, which is also a good use case for referencing.
When modeling data in NoSQL, we need to consider how the application queries and uses the data. This helps us decide whether to store data in a single document or to have a main document with references. Otherwise, we might need to write queries that pull information from multiple collections, which can severely impact application performance and create a poor user experience.
As a mnemonic, I like to think of NOSQL as "Normalization Off SQL."
MongoDB Terminologies
- Collections: Equivalent to tables in relational databases.
- Documents: Equivalent to rows in relational databases.
- Columns: Also known as attributes or fields within a BSON document.
Microservices Architecture
In a microservices architecture, each service has its own data storage or database. This approach adheres to the Single Responsibility Principle (SRP) of the SOLID principles, which states that a class or module should have only one reason to change.
By breaking down the monolith, each microservice can manage its own data store, leading to better scalability, maintainability, and independence among services.
Thanks
Sreeni Ramadurai
Top comments (0)