In the world of databases, a data model is like a “shelf” for organizing information. Different database models have completely different design philosophies for these shelves. As a popular document - oriented database, MongoDB is most impressive for its flexible data model. Today, we’ll use simple examples to discuss why MongoDB’s data model is more “flexible” than traditional relational databases.
First, let’s talk about the data model of relational databases: a fixed “table shelf”¶
Relational databases (such as MySQL and PostgreSQL) are centered around “tables”. Imagine you have a “user table” that must have fixed columns (fields), such as: id (user ID), name (name), age (age), email (email), and address (address). These columns are designed in advance, like a fixed table template.
For example, to store information about “user Alice” in a relational database:
-- Relational database: User table (all possible fields must be defined in advance)
CREATE TABLE users (
id INT PRIMARY KEY,
name VARCHAR(50),
age INT,
email VARCHAR(100),
address_street VARCHAR(100), -- Address field
address_city VARCHAR(50), -- Address field
-- If you want to add a "hobbies" field, you must first modify the table structure!
);
-- Insert data (assuming you want to add a "hobbies" field, you must first execute ALTER TABLE)
INSERT INTO users (id, name, age, email, address_street, address_city)
VALUES (1, 'Alice', 25, 'alice@example.com', 'Main St', 'NY');
Here’s the problem: If the requirements suddenly change, for example, if you want to add “interests” (such as “reading” and “sports”) to the user, the relational database must first modify the table structure (using ALTER TABLE), otherwise, the new field cannot be stored. This “fixed shelf” design is not friendly to business requirements that change rapidly.
MongoDB’s data model: a free “document box”¶
MongoDB is a document - oriented database. It stores data as JSON - like “documents” (Documents) instead of fixed tables. Each document can have its own “fields”, and different documents can even have different fields. It is like a “scalable box” — you can put things in it at any time without having to pre - define what must be put in it.
To store the information of “user Alice” in MongoDB:
// MongoDB collection (Collection): users, document (Document)
{
"_id": 1, // MongoDB automatically generates a unique ID (similar to the primary key in relational databases)
"name": "Alice",
"age": 25,
"email": "alice@example.com",
"address": { // Nested address information, more compact structure
"street": "Main St",
"city": "NY"
},
"hobbies": ["reading", "coding"] // Add the "hobbies" field directly
}
Key difference: MongoDB documents do not need to pre - define all fields. When adding new fields, you can directly write them in the document without modifying the “shelf”. For example, if the next requirement is to add “work unit”, you can directly add a field to the document:
{
"_id": 1,
"name": "Alice",
"age": 25,
"email": "alice@example.com",
"address": {"street": "Main St", "city": "NY"},
"hobbies": ["reading", "coding"],
"company": "Tech Corp" // Add new fields directly without modifying the structure!
}
The core advantages of MongoDB’s flexibility: why is it more “flexible”?¶
1. Non - fixed field structure, no pre - definition required¶
The table in a relational database is like a “standardized shelf” where every position must have a product; while MongoDB’s document is a “personalized box” where each document can only store what it needs. For example:
- In a relational database, a “product table” needs to pre - set all possible attributes (such as price, inventory, color, size, weight, etc.). Otherwise, when adding new attributes, the table structure must be modified.
- In MongoDB, each product document can store only the attributes it has: a mobile phone document may be {"brand": "Apple", "price": 999, "camera": 12}, while a clothing document may be {"brand": "Nike", "size": "M", "color": "red"}. There is no need to pre - set attribute columns at all.
2. Nested structure, more compact data¶
In a relational database, complex data (such as “user’s address” and “order’s product list”) requires foreign key association with multiple tables. For example, the user table and the address table are associated through user_id. When querying user information, you need to query the user table first, then the address table, and finally merge the results with JOIN, which is a complex process.
MongoDB can directly put the nested structure into the document. For example, the user’s address and user information can be placed in the same document:
{
"_id": 1,
"name": "Alice",
"address": {
"street": "Main St",
"city": "NY",
"zipcode": "10001"
},
"orders": [ // Nested order list
{"order_id": 101, "date": "2023 - 01 - 01", "items": ["book", "pen"]},
{"order_id": 102, "date": "2023 - 02 - 01", "items": ["laptop"]}
]
}
This nested structure makes the data more compact, and there is no need to associate multiple tables when querying. You can directly access nested fields.
3. Quickly adapt to changing requirements, suitable for agile development¶
In actual development, requirements often change. For example:
- In a relational database: Suppose the user information is expanded from “name, age, phone” to “interests, consumption records, family relationships”. Each time you add a new field, you must modify the table structure, which may lead to database table expansion, performance degradation, and even require downtime for maintenance.
- In MongoDB: When requirements change, you can directly add new fields to the document. For example, add hobbies (interests) and spending_records (consumption records) to the user document. There is no need to modify the entire collection structure, which is more efficient in development, especially suitable for “rapid iteration” agile development.
4. More efficient storage of “sparse data”¶
Some data attributes are naturally “unified”. For example:
- In a relational database, if a “product table” is used to store information about different types of products (mobile phones, clothes, food), you must design columns for all possible attributes (such as “camera parameters of mobile phones”, “size of clothes”, “shelf life of food”). This leads to a large number of empty columns in the table (for example, the “shelf life” field of mobile phones is empty, and the “camera parameters” field of clothes is empty), which wastes storage space.
- In MongoDB, each product document only stores the attributes it has, and there is no waste of empty columns: a mobile phone document stores {"camera": 12, "battery": 4000}, and a clothing document stores {"size": "M", "material": "cotton"}. The structure is clear and efficient.
Summary: Who is MongoDB’s flexibility suitable for?¶
MongoDB’s flexible data model makes it particularly suitable for the following scenarios:
- Rapidly iterating businesses: For example, Internet startup projects with rapidly changing requirements can quickly add fields to adapt to new needs.
- Complex nested data: Such as e - commerce product details (including pictures, specifications, inventory) and user behavior logs (including multi - dimensional attributes).
- Scenarios with non - uniform data structures: Such as IoT device data (different sensors of different devices have different parameters) and log data (different services have large differences in log formats).
Of course, flexibility also needs to be used reasonably — for example, excessive nesting may lead to slower queries. MongoDB also provides functions such as indexing and aggregation to optimize performance. But for beginners, understanding the core of “document model is more flexible than table model” can help you quickly get started with MongoDB data design and make development smoother.
If you are just starting to contact databases, MongoDB’s “document model” may be closer to your real data structure than the “table model” of relational databases (such as your Moments data, shopping cart data). Try storing a few simple documents with it, and you’ll find that organizing data is really more free!